Study data structure in the university to learn the bubbling method, as a comparison of the classic sorting mode because of its time is more complex as an entry-level algorithm, although the bubbling algorithm in practical applications, but also has a certain amount of research value, here give three kinds of implementation, the first is the original algorithm time complexity of O (n); The second is to join the flag, so that the algorithm in order to sort the data has been ordered before the end of the early; the third, record the small subscript of the last two elements exchanged after each trip and use it as the upper limit of the next sort, so that the algorithm can reduce the number of comparisons directly across the trailing ordered data elements in the data to be sorted
Bubble sort Primitive Algorithm:
#include <iostream>using namespacestd;template<classT>voidBUBBLESORT_0 (T a[],intN) { for(intI=1; i<n; i++) { for(intj=0; j<n-i;j++) { if(a[j]>a[j+1]) {swap (a[j], a[j+1]); } } }}
After adding the flag bit:
Template <classT>voidBubblesort_1 (T a[],intN) { intflag=1; for(intI=1; I<n && Flag; i++) {flag=0; for(intj=0; j<n-i;j++) { if(a[j]>a[j+1]) {swap (a[j], a[j+1]); Flag=1; } } }}
Record the smaller subscripts in the last pair of elements exchanged for each trip
Template <classT>voidBubblesort_2 (T a[],intN) { intI, J; intLastexchangeindex; I=n-1; while(i>0) {Lastexchangeindex=0; for(j=0; j<i;j++) { if(a[j]>a[j+1]) {swap (a[j], a[j+1]); Lastexchangeindex=J; }} I=Lastexchangeindex; }}
Main function:
intMain () {inta[]={8,6,9,7,5,0,4,1,3,2}; intn=Ten; Bubblesort_2 (A, N); for(intI=0; i<n;i++) cout<<A[i]<<" "; cout<<Endl; return 0;}
------Bubbling method of exchange sorting and its optimization