Two ways to sort the bubble sort algorithm

Source: Internet
Author: User

Bubble sort is a sort algorithm, clear thinking, code concise, often used in college students computer courses.

Bubble sort There are two ways, the next two number comparison, the large number (or small number) on the top, sequentially, like blisters, gradually floating.

It is also possible to put the larger number (or smaller number) below and push it into the bottom of the lake in the opposite process. Both of these methods are bubble sort, because the bubble sort is compared with two adjacent numbers, subscript is not jumping, and is also a stable algorithm.

Method One: The larger number (or the smaller number) floats

1 voidBubblesort (intA[],intN)2 {3      for(intI=0; i<n-1; i++)4     {5         BOOLissorted =true;6          for(intj=n-1; j>i; j--)7         {8             if(A[j] < a[j-1])9             {Tenissorted =false; One                 //Exchange A                 intTMP = a[j-1]; -a[j-1] =A[j]; -A[J] =tmp; the             } -         } -         if(issorted)////If no swap occurs, the array is sorted. -              Break; +     } -}

The second loop, that is, the subscript of J, is carried forward from behind.

Way two: larger (or smaller) pushes into the bottom of the lake

1 voidBubblesort (intA[],intN)2 {3      for(intI=0; i<n-1; i++)4     {5         BOOLissorted =true;6          for(intj=0; J < n-i-1; J + +)7         {8             if(A[j] > a[j+1])9             {Tenissorted =false; One                 //Exchange A                 intTMP =A[j]; -A[J] = a[j+1]; -a[j+1] =tmp; the             } -         } -         if(issorted) -              Break; +     } -}

Modify the 8th line of code, modify the size of the number, you can achieve is from small to large arrangement, or from large to small.

The second loop, which is the subscript of J, is from the back of the trip.

Reference: http://c.biancheng.net/cpp/html/2443.html

Http://www.cnblogs.com/qq329914874/p/6002297.html

Two ways to sort the bubble sort algorithm

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.