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