Sorting Algorithm (1) -- Bubble sorting and Improvement

Source: Internet
Author: User

Sorting Algorithm (1) -- Bubble sorting and Improvement

Bubble Sorting

The efficiency of Bubble Sorting is very low, but the algorithm implementation is very simple, so it is very suitable for the entry-level Algorithm for sorting research.

 

Basic Ideas

Compare and adjust the numbers of adjacent numbers from top to bottom in order to let the larger numbers sink, while the smaller numbers go up. That is, when two adjacent numbers are compared and they are found to have different sorting requirements, they are exchanged. Each traversal determines that a maximum value is placed at the end of the array to be arranged. The next traversal will not sort the maximum value and the elements after it (it has been sorted ).

 

 

Java Implementation

 

 

Public class Sort {private int [] array; public Sort (int [] array) {this. array = array;} // print the public void display () {for (int I = 0; iarray [j]) element in the array in sequence. {// if the former is greater than the latter, the swap location temp = array [J-1]; array [J-1] = array [j]; array [j] = temp ;}} system. out. print (the + (I + 1) + round sorting result :); display ();}}}


 

Test:

 

Public static void main (String [] args) {int [] a = {, 18}; Sort sort = new Sort (a); System. out. print (unordered result :); sort. display (); sort. bubbleSort ();}


 

Print result:

 

 

 

Algorithm Analysis

In the above example, a total of seven numbers are waiting for the array to be sorted, 6 comparisons are performed in the first round of sorting, 5 comparisons are performed in the second round of sorting, and so on, A comparison is made in the last round.

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

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

In this way, the algorithm is compared about N2/2 times. Because data is exchanged only when the preceding element is greater than the latter, the number of exchanges is less than the comparison. 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, that is, when the initial data is in reverse order, each comparison needs to be exchanged ).

The number of exchange and comparison operations is proportional to N2. In the large O notation, constants are ignored,The time complexity of Bubble Sorting is O (N2).

The time complexity of O (N2) is a bad result, especially when the data volume is large. Therefore, Bubble Sorting is usually not used in practical applications.

 

Improvement of Bubble Sorting

As we have analyzed above, the efficiency of Bubble Sorting is relatively low, so we need to improve it through various methods.

The simplest way to improve is to add a symbolic variable exchange to indicate whether data exchange exists in a sorting process. If data exchange is not performed during a sorting, it indicates that the data has been arranged as required, and the sorting can be completed immediately to avoid unnecessary comparison process.

In the above example, the entire array is actually ordered after the fourth round of sorting, and the comparison between the last two rounds is unnecessary.

The improved code is as follows:

 

// Bubble sort Improvement 1 public void bubbleSort_improvement_1 () {int temp; int len = array. length; for (int I = 0; I
  
   
Array [j]) {// if the former is greater than the latter, the swap location temp = array [J-1]; array [J-1] = array [j]; array [j] = temp; if (! Exchange) exchange = true; // exchange occurred} System. out. print (the + (I + 1) + round sorting result :); display (); if (! Exchange) break; // if data is not exchanged in the previous round, it turns out that the data has been sorted and ended }}
  

Test with the same initial array and print the result as follows:

 

 

The above improvement method is to identify whether data exchange has occurred in the last round of sorting. Further think, if only a few elements in the next section do not have data exchange in the last round of sorting, is it possible to determine that this section does not need to be compared? The answer is yes.

For example, in the preceding example, the sorting result of the first four rounds is:

 

Unordered results: 1 5 4 11 2 20 18

1st round sorting result: 1 4 5 2 11 18 20

2nd round sorting result: 1 4 2 5 11 18 20

3rd round sorting result: 1 2 4 5 11 18 20

4th round sorting result: 1 2 4 5 11 18 20

 

After 1st rounds of sorting, 11, 18, and 20 are already ordered. After several sorting times, their positions remain unchanged. However, according to the bubble algorithm, we will continue to participate in the comparison in the 2nd round, and we will continue to participate in the comparison in the 2nd and 3rd rounds during the 11 round, which is actually useless.

We can further improve the algorithm by setting a pos pointer. The data after the pos is not exchanged in the last round of sorting. In the next round of sorting, the data after the pos is no longer compared.

The code is changed as follows:

 

// Bubble Sorting Improvement 2 public void bubbleSort_improvement_2 () {int temp; int counter = 1; int endPoint = array. length-1; // endPoint indicates the subscript of the last element to be compared while (endPoint> 0) {intpos = 1; for (int j = 1; j <= endPoint; j ++) {if (array [J-1]> array [j]) {// if the previous digit is greater than the last one, the swap location temp = array [J-1]; array [J-1] = array [j]; array [j] = temp; pos = j; // a data exchange occurred between the element whose subscript is j and the element whose subscript is J-1} endPoint = pos-1; // only the element whose subscript is smaller than pos is sorted in the next round, the elements with a subscript greater than or equal to the pos have already ranked System. out. print (+ counter + round sorting result :); display ();}}

 

There is no best algorithm, but better. In fact, the above two improvement methods are temporary and non-permanent. They are a kind of improvement. Next we will give you an improvement on the "bottom-up pay-as-you-go" method.

The traditional bubble algorithm only determines the maximum value for each sort. We can perform two positive and negative bubbles in each loop to find the maximum and minimum values respectively, so that the number of rounds of sorting can be reduced by half.

The improved code is as follows:

 

// Bubble Sorting IMPROVEMENT 3 public void bubbleSort_improvement_3 () {int temp; int low = 0; int high = array. length-1; int counter = 1; while (low
  
   
Array [I + 1]) {// if the first digit is greater than the last one, the swap location temp = array [I]; array [I] = array [I + 1]; array [I + 1] = temp;} -- high; for (int j = high; j> low; -- j) {// reverse bubble, determine the minimum value if (array [j]
   

 

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.