Sort algorithm (i)--bubble sort and improvement

Source: Internet
Author: User

Bubble sort

Bubble sorting is inefficient, but the algorithm is very simple to implement, so it is suitable as an entry algorithm for research sequencing.


Basic ideas

To the current not well-sequenced range of all the number, the top-down to the two adjacent to the number of comparison and adjustment, so that the larger number sinking, the smaller number up. That is, they are exchanged when the comparison of the two adjacent numbers reveals that their ordering is the opposite of the Order's requirements. Each traversal determines that a maximum value is placed at the end of the array to be sorted, and the next traversal, the maximum value and the elements after it are no longer ordered (already queued).



Java implementation

public class sort{   private int [] array;   public Sort (int [] array) {     This.array = array;  }   Prints the elements in the array in order public  void display () {     i=0;i<array.length;i++ (int) {         System.out.print (array[i]+ "\ T ");     }     System.out.println ();  }   Bubble sort public  void Bubblesort () {     int temp;     int len = array.length;         for (int i=0;i<len-1;i++) {  //outer loop: A relative maximum element is determined once per loop for         (int j=1;j<len-i;j++) {  // Inner Loop: There is an element of I that has been lined up, according to I determine the comparison number if            (Array[j-1]>array[j]) {  //If the previous bit is greater than the last bit, swap position                temp = array[j-1];                ARRAY[J-1] = array[j];                ARRAY[J] = temp;            }         }         System.out.print ("First" + (i+1) + "wheel sort Result:");         Display ();     }  } }


Test:

public static void Main (string[] args) {     int [] a = {1,5,4,11,2,20,18};     Sort sort = new sort (a);     System.out.print ("Results when not sorted:");     Sort.display ();     Sort.bubblesort ();       }


Printing results:




Algorithm analysis

In the example above, there are 7 numbers in the array to be sorted, 6 comparisons were made in the first round, 5 comparisons were made in the second round, and so on, and the last round was compared.

The total number of elements to be added is N, and the number of comparisons required is:

(N-1) + (N-2) + (N-3) + ... 1=n* (N-1)/2

In this way, the algorithm makes approximately N2/2 comparisons. Because the data is exchanged only when the preceding element is larger than the subsequent element, the number of interchanges is less than the number of comparisons. If the data is random and about half of the data needs to be exchanged, the number of exchanges is N2/4 (but in the worst case, when the initial data is reversed, each comparison needs to be exchanged).

The number of operations exchanged and compared is proportional to the N2, because in large o notation, the constant is ignored and the time complexity of the bubble sort is O (N2).

The time complexity of O (N2) is a poor result, especially in the case of a large amount of data. So bubble sort is not usually used for actual applications.


Improvements in bubbling sorting

It has been analyzed above, the efficiency of bubble sorting is relatively low, so we have to improve by various methods.

The simplest way to improve is to add a symbolic variable exchange, which is used to flag whether there is data exchange during a certain trip, and if there is no data exchange during a certain trip, then the data has been arranged as required, and the sorting can be completed immediately to avoid unnecessary comparison process

In the above example, after the fourth round of sorting, the whole array is already in order, and the last two rounds are not necessary.

The improved code is as follows:

Bubbling sort improvements 1 public  void Bubblesort_improvement_1 () {     int temp;     int len = array.length;         for (int i=0;i<len-1;i++) {          Boolean exchange = FALSE;  Set interchange variable         for (int j=1;j<len-i;j++) {             if (Array[j-1]>array[j]) {  //If the previous bit is greater than the last bit, swap position                temp = array[ J-1];                ARRAY[J-1] = array[j];                ARRAY[J] = temp;                               if (!exchange) Exchange =true;  An interchange operation occurred            }         }         System.out.print ("i+1" + "wheel sort Result:");         Display ();         if (!exchange) break;  If the last round does not have Exchange data, the proof is already orderly, end sort     }   }

With the same initial array test, the print results are as follows:

The above improvement method is based on the previous round of sorting there is no data exchange as the identification, further thinking, if the last round of sorting, only a few elements of the latter paragraph did not happen to exchange data, is it possible to determine that this paragraph does not have to be compared? The answer is yes.

For example, in the above example, the first four rounds of the order result are:


Results when not sorted: 1 5 4 11 2 20 18

1th round sorted Results: 1 4 5 2 11 18 20

2nd round sorted Results: 1 4 2 5 11 18 20

3rd round sorted Results: 1 2 4 5 11 18 20

4th round sorted Results: 1 2 4 5 11 18 20


After the 1th round of sorting, 11, 18, 20 are already orderly, after several sorts of their position has not changed, but according to the bubble algorithm, 18 will still participate in the 2nd round, 11 will still be in the 2nd round, 3rd round of participation in the comparison, in fact, are useless.

We can further improve the algorithm: set a POS pointer, the data after the POS is not exchanged in the previous round of sorting, the next round of sorting, the data after the POS is no longer compared.

The code changes are as follows:

Bubbling sort improvements 2 public   void Bubblesort_improvement_2 () {       int temp;       int counter = 1;       int endPoint = array.length-1;  EndPoint represents the last element to be compared subscript             while (endpoint>0) {           intpos = 1;          for (int j=1;j<=endpoint;j++) {if                (Array[j-1]>array[j]) {  //If the previous bit is greater than the last bit, swap position                 temp= array[j-1];                 array[j-1]= Array[j];                 array[j]= temp;                                     Pos= J;  The element with the subscript J and the element with the subscript j-1 has a data exchange              }          }          endpoint= pos-1;  The next round of sorting only the elements below the Pos are ordered, the subscript is greater than or equal to the POS element has been lined up                   System.out.print ("+counter+" Wheel sorting results: ");          Display ();       }   }

For the algorithm, there is no best, only better. The above two methods of improvement in fact, is a palliative, is a "Yantang" improvement, below we have a "drastic" improvement.

The traditional bubbling algorithm only determines the maximum value per order, and we can bubble up and down two times in each loop, finding the maximum and minimum values, so that the number of wheels in the order is halved.

The improvement code is as follows:

Bubbling sort improvements 3 public   void Bubblesort_improvement_3 () {       int temp;       int low = 0;       int high = array.length-1;       int counter = 1;       while (Low


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

Sort algorithm (i)--bubble sort and improvement

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.