Sort algorithm Series--bubble sort

Source: Internet
Author: User
Tags comparable

Bubble sort is a kind of exchange sort, the idea is to step backwards from the head of the sequence, each traversal compares the adjacent two elements, if the order is not the exchange, the sequence after the N-1 traversal is completed. Because each traversal is the largest element of the last move, similar to the bubble slowly surfaced, hence the name bubbling algorithm. The idea of a bubbling algorithm is simple, easy to implement, but inefficient, so even small data volumes are rarely recommended for use with bubble algorithms, and more use of direct insertion sorting.
Basic Idea :
Starting from the beginning of the sequencing sequence to iterate through the n-1 times, each traversal compares the adjacent two elements, if the order is not the exchange, that is, if you want to be small to large, then if the next two elements of the comparison result is greater than the previous, then the exchange is possible, Then the end of the sequence is reached by traversing the largest element one at a time, and the sequence is sorted after the n-1 traversal. There is obviously room for optimization, as mentioned below.
key points of implementation :
The i=0...n-1 traversal is compared from 0 to n-1-i (n sequence length) because each traversal moves the most unsorted elements to the end of the sequence, so the tail of the sequence is ordered, so there is no need to continue the more orderly part of the subsequent traversal.
Algorithm Improvements :
The algorithm has two areas that can be optimized:

    • If no interchange occurs during a traversal, that is, the order of all neighboring elements is correct, then the entire sequence has been sorted so that no further traversal is necessary.
    • During each traversal, the last occurrence of the Traverse is recorded, and the part after the change is already ordered, and can be ended prematurely the next time it is traversed.

The experiment shows that the efficiency of the above two kinds of improvements is not greatly improved, the first improvement efficiency is lower than the improvement, the second kind of improvement efficiency is slightly improved a little. While these two improvements are theoretically somewhat optimized, the sequences used in the test are generally random, that is, the possibility of sorting and partially ordering before the n-1 traversal is very small, so the effects of both improvements are not obvious and may not occur at all. Instead, some logic judgments result in lower efficiency. But if it is real data, then the two cases mentioned earlier are likely to happen.

Java implementations :

 PackageCom.vicky.sort;ImportJava.util.Random;/** * Exchange sort: bubble sort * * time complexity: O (n^2) * Space complexity: O (1) * * Stability: Stable * * @author Vicky * */ Public  class bubblesort {    /** * Not improved bubble sort * * @param <T> * @param Data */     Public Static<t extends Comparable<t>>void Sort(t[] data) {LongStart = System.nanotime ();if(NULL= = data) {Throw NewNullPointerException ("Data"); }if(Data.length = =1) {return; }//n-1 traversal         for(inti =0; I < data.length-1; i++) {//Each traversal starts from 0 and compares adjacent elements in turn             for(intj =0; J < Data.length-1I J + +) {//Front element > back element swap                if(Data[j].compareto (Data[j +1]) >0) {T temp = data[j]; DATA[J] = data[j +1]; Data[j +1] = temp; }}} System.out.println ("Sort, use time:"+ (System.nanotime ()-start)/1000000); }/** * Improved bubble sort * * Improved principle: If a traversal process does not occur, the sequence is already ordered, so no further traversal is required. * * @param <T> * @param Data * *     Public Static<t extends Comparable<t>>void Sortimprove(t[] data) {LongStart = System.nanotime ();if(NULL= = data) {Throw NewNullPointerException ("Data"); }if(Data.length = =1) {return; }BooleanExchange =false;//Record a trip whether the interchange occurred        //n-1 traversal         for(inti =0; I < data.length-1; i++) {//Each traversal starts from 0 and compares adjacent elements in turn             for(intj =0; J < Data.length-1I J + +) {//Front element > back element swap                if(Data[j].compareto (Data[j +1]) >0) {T temp = data[j]; DATA[J] = data[j +1]; Data[j +1] = temp; Exchange =true; }            }//If the loop does not have an interchange, then the sequence is ordered and no further traversal is required            if(!exchange) {return; }} System.out.println ("sortImprove1, use time:"+ (System.nanotime ()-start)/1000000); }/** * Improved bubble sort * * Improved principle: In each scan of bubbling sequencing, remember where the last swap occurred lastexchange can also help. Because the part after the position is already ordered (no exchange, * so is ordered), * so the next trip to the beginning of the sort, just 0 to lastexchange part, Lastexchange to N-1 is ordered area. At the same time, if no swap occurs, you can exit * * @param <T> * @param Data */     Public Static<t extends Comparable<t>>void SortImprove2(t[] data) {LongStart = System.nanotime ();if(NULL= = data) {Throw NewNullPointerException ("Data"); }if(Data.length = =1) {return; }intLastchange = Data.length-1;//Record a trip to the location where the last interchange occurred, after which the position was ordered        //Last traversal occurred lastchange>0, continue traversal         while(Lastchange >0) {//The end of this traversal from 0 to the last time the last interchange was traversed            intend = Lastchange; Lastchange =0;//Each traversal starts from 0 and compares adjacent elements in turn             for(intj =0; J < End; J + +) {//Front element > back element swap                if(Data[j].compareto (Data[j +1]) >0) {T temp = data[j]; DATA[J] = data[j +1]; Data[j +1] = temp; Lastchange = j +1; }}} System.out.println ("SortImprove2, use time:"+ (System.nanotime ()-start)/1000000); } Public Static void Main(string[] args) {//Used to record three kinds of bubble sort        Long[] useTime1 =New Long[Ten];Long[] useTime2 =New Long[Ten];Long[] UseTime3 =New Long[Ten];//Cycle Test 10 times, take mean value         for(intTimes =0; Times <Ten; times++) {//Build a sequence of 10,000 elements to sortRandom ran =NewRandom (); integer[] data =Newinteger[10000]; for(inti =0; i < data.length; i++) {Data[i] = Ran.nextint (10000000); }//Use System.arraycopy to copy three arrays for sortinginteger[] Data1 =NewInteger[data.length]; integer[] Data2 =NewInteger[data.length]; integer[] Data3 =NewInteger[data.length]; System.arraycopy (data,0, Data1,0, data.length); System.arraycopy (data,0, Data2,0, data.length); System.arraycopy (data,0, Data3,0, data.length);//Record the time of three bubble sorting separately            LongStart = System.nanotime ();            Bubblesort.sort (DATA1); Usetime1[times] = (System.nanotime ()-start)/1000000;//Sortutils.printarray (DATA1);Start = System.nanotime ();            Bubblesort.sortimprove (DATA2); Usetime2[times] = (System.nanotime ()-start)/1000000; Start = System.nanotime ();//Sortutils.printarray (DATA2);Bubblesort.sortimprove2 (DATA3); Usetime3[times] = (System.nanotime ()-start)/1000000;//Sortutils.printarray (DATA3);}//Calculation time max, Min, mean        Long[] res1 = Sortutils.countarray (useTime1);Long[] Res2 = Sortutils.countarray (useTime2);Long[] Res3 = Sortutils.countarray (UseTime3); System.out.println ("Method\tmax\tmin\tavg\t"); System.out.println ("Sort"+"\ T"+ res1[0] +"\ T"+ res1[1] +"\ T"+ res1[2]); System.out.println ("Sortimprove"+"\ T"+ res2[0] +"\ T"+ res2[1]                +"\ T"+ res2[2]); System.out.println ("SortImprove2"+"\ T"+ res3[0] +"\ T"+ res3[1]                +"\ T"+ res3[2]);///test results, the first method of improvement is less efficient than no improvement,        //May be less likely due to early completion of sorting, adding too many assignments per traversal and judging the operation resulting in reduced efficiency        ///The second improvement method still has some effect        //Method Max min avg        //Sort 1190 1073 1123        //Sortimprove 1258 1097 1146        //SortImprove2 1205 1056 1099}}

Efficiency Analysis :
(1) Complexity of time
O (n^2)
The best time complexity for bubbling sorting is O (n), one-time traversal, no swap (the first improvement). The worst case needs to traverse n-1 times, compare and exchange n-1-i times, so the time complexity is O (n^2).
(2) Complexity of space
O (1)
In terms of space, it requires only an element of auxiliary space for the position of the element to Exchange O (1).
(3) Stability
Stability
The relative position of the two identical elements does not change because only two adjacent elements are exchanged during the sorting process, and the same elements are not exchanged to reduce the number of interchanges.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Sort algorithm Series--bubble sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.