Bubble sort Basic code and its optimization

Source: Internet
Author: User

Bubble sort is a sort of exchange, and its basic idea is that 22 compares the keywords in a sequence of sentences , if the inverse is exchanged, until there is no reverse order. It runs as follows (in ascending order, for example):

      1. Compare the elements of a sentence . 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. When this is done, the final element will 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.

For example, the sequence array to be sorted is: 9 2 6 8 7 3 1 0 4 5, sorted in ascending order of 0 1 2 3 4 5 6 7 8 9, following the bubbling method described above:

  9 2 6 8 7 3 1 0 4 5 adjacent record keywords for comparison, 9>2 Exchange to get sequence:2 9 6 8 7 3 1 0 4 5

2 9 6 8 7 3 1 0 4 5 Same, 9>6, Exchange: 2 6 9 8 7 3 1 0 4 5

2 6 9 8 7 3 1 0 4 5 9>8 Exchange received: 2 6 8 9 7 3 1 0 4 5

.....

2 6 8 7 3 1 0 4 9 5 9>5 Exchange Received: 2 6 8 7 3 1 0 4 5 9

After a N-1 comparison, you can see that the largest element of the keyword 9 has been bubbled up to the end of the sequence in ascending order, a process known as the first bubbling sort. The second order begins with the first pair of adjacent elements of the sequence:

  2 6 8 7 3 1 0 4 5 9-->2 6 8 7 3 1 0 4 5 9

2 6 8 7 3 1 0 4 5 9-->2 6 8 7 3 1 0 4 5 9

2 6 8 7 3 1 0 4 5 9-->2 6 7 8 3 1 0 4 5 9

....

2 6 7 3 1 0 4 8 5 9-->2 6 7 3 1 0 4 5 8 9

The second pass is completed and the keyword 8 is promoted to the second-to-last position in the sequence. It can be found that the second order of comparison is less than the first trip, 8 and the last 9 is not compared.

After you repeat this process for N-1 comparisons, you can complete the bubbling ordering of the entire sequence.

According to this idea, the corresponding code is:

voidBubbleSort1 (intArray[],intarraylength) {    intI, J;  for(i=0; i<arraylength-1; ++i)//make a N-1 trip comparison    {         for(j=1; j<arraylength-i;++j)//internal loops in each comparison            if(array[j]<array[j-1])//that is, the comparison between adjacent elementsSwap (Array[j],array[i]);//reverse order, to exchange    }}

Notice that when I write the bubble sort definition, the red font emphasizes that the bubbling sort is compared with the adjacent elements, such as the following code, which is structurally much like bubbling, is actually simply a sort of exchange:

voidSort (intArray[],intarraylength) {    intI, J;  for(i=0; i<arraylength-1; ++i)    {         for(j=i+1; j<arraylength;++j)if(Array[j]<array[i])//the non-contiguous elements are compared here. The algorithm is not bubblingSwap (Array[j],array[i]); }}

This algorithm does a lot of useless switching operations, the efficiency is very low.

The sorting algorithm can also be optimized to set a flag field flag, which is true if a shift has occurred. If no interchange occurs for a particular trip, then the sequence is ordered and no further comparison operation is required, and flag is false at this time.

{    intI, J; BOOLFlag =true;  for(i=0; i<arraylength-1&&flag;++i){flag=false;  for(j=1; j<arraylength-i;++j)if(array[j]<array[j-1]){Swap (array[j],array[j-1]); Flag =true;    //There is an exchange indicating that the current sequence is not yet ordered, and the flag is ture } }}

The Bubbling method also has another optimization, which is to sort out only the unordered keywords. Assuming that the sequence array={2,1,5,4,0,6,7,8,9} is sorted in ascending order, you only need to sort the unordered area {2,1,5,4,0}. Use a flag to record the range of unordered areas:

voidBUBBLESORT3 (intArray[],intarraylength) {    intFlag = arraylength-1;  while(flag>0)    {         for(inti =0; i<arraylength-1; i++)        {            intK =Flag; Flag=0;  for(intj =0; j<k;++j)if(array[j]<array[j+1]) {Swap (array[j],array[j+1]); Flag=J;        //Record the end position of the unordered area } }    }}

Of course, this optimization is a bit special, but the sequence is not optimized when it is completely reversed.

In general, the efficiency of bubble sorting is lower in the case of small amount of data can be used, otherwise you should choose another sorting algorithm.

This article by the sentence Daquan Www.zaojuzi.com finishing release


Bubble sort Basic code and its optimization

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.