Optimization and misunderstanding of bubble sort

Source: Internet
Author: User

Bubble sort (Bubble sort) is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.

The bubbling sorting algorithm works as follows:

    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
    3. Repeat the above steps for all elements, except for the last one.
    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.

//-----------------------------------------------------

Normal Bubble Sort code:

1  Public classbubblesort{2       Public Static voidMain (string[] args) {3          intScore[] = {67, 69, 75, 87, 89, 90, 99, 100};4           for(inti = 0; i < score.length-1; i++) {//up to do n-1 sort of trip5               for(intj = 0; J < score.length-i-1; J + +) {//sort the current unordered interval score[0......length-i-1] (the range of J is critical, the range is gradually shrinking)6                  if(Score[j] < Score[j + 1]) {//swap the small value to the back7                      inttemp =Score[j];8SCORE[J] = score[j + 1];9Score[j + 1] =temp;Ten                  } One              }             ASystem.out.print ("First" + (i + 1) + "secondary" results: "); -               for(intA = 0; A < Score.length; a++){ -System.out.print (Score[a] + "\ T"); the              } -System.out.println (""); -          } -System.out.print ("Final sort result:"); +               for(intA = 0; A < Score.length; a++){ -System.out.print (Score[a] + "\ T"); +         } A      } at}

So that's the problem? In the sorting process found that the following elements are already in order, then the continuation of the convenience is wasted, so increase the flag flag, for early termination

Improve the efficiency of the algorithm

1 /**2 * cause, when bubbling sort finds elements are already sorted out, and does not stop this will be a waste of time complexity. 3 * Analysis: When the large number is constantly moving back, the next time the sorting test again found that the current is already in sequence, then no longer continue to loop directly out4 * The time-saving complexity here is worth it: the number of times for the For loop is reduced: for example {1, 3, 2, 9, 4}5 * After the first bubble becomes {1,2,3,4,9}, the flag at this time is still false, then continues the next wave of outer loop, flag is true, but the internal for loop still has to go through6 * This is necessary, otherwise it will be as strong as the second optimization, in the internal for loop, there is no time to enter the if judgment, indicating that the array in front of the maximum number of already ranked is already ordered7 * This should only be a break, and this optimization is only partially optimized for bubbling. 8  */9  Public classBubblesortanalyse {Ten  One      Public Static int[] Sort (int[] data) { A         inttemp; -         BooleanFlag =false; -  the          for(inti = 0; i < data.length-1; i++) { -Flag =true; -              for(intj = 0; J < data.length-i-1; J + +) { -                 if(Data[j] > data[j + 1]) { +temp =Data[j]; -DATA[J] = data[j + 1]; +Data[j + 1] =temp; AFlag =false; at                 } -             } -             //if the last bubble sort is all in order -             //that is, Flag!=false, then exit directly, without the next round of bubbling cycle, improve efficiency, otherwise the array has been ordered, he will continue to bubble cycle -             if(flag) { -                  Break;//You can annotate this line, step through the test or view the value of I to verify in             } -             //System.out.println (i); to         } +         returndata; -     } the  *     //Bubble Sort optimization, judging by flag whether the sort has ended prematurely.  $     //the optimization is flawed, and when the smallest number is probably still in the sorted array, it has been stopped.Panax Notoginseng     // -      Public Static voidBubblesort (int[] arr) { the         intn =arr.length; +         intI, J, temp, flag;//Temp temporary variable, flag whether flag is terminated prematurely Aflag = 1;//flag equals 1 means the loop is not over, 0 means the loop is over the         //Bubble Sort +          for(i = 1; i < n && flag = = 1; i++) { -              for(j = 0; J < N-i; J + +) { $                 //if the subsequent loop does not change the value of the flag, the array Exchange does not occur $                 //that means the array is already in order.  -Flag = 0; -                 if(Arr[j] > arr[j + 1]) { the                     //as long as it's one time, it needs to be 1 . -Flag = 1;Wuyi                     //Exchange thetemp =Arr[j]; -ARR[J] = arr[j + 1]; WuArr[j + 1] =temp; -                 } About  $             } -         } -     } -  A      Public Static voidMain (string[] args) { +         int[] arr = {2, 3, 9, 1, 10 }; the         //Bubblesort (arr); -         int[] arr2 =sort (arr); $          for(inti:arr2) { the System.out.println (i); the         } the     } the}

The specific comments in the code are explained in detail.

Optimization and misunderstanding of bubble sorting

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.