Basic idea:
In the set of numbers to be sorted, the total number in the range that is not currently in sequence, the top-down pairs of adjacent two numbers are compared and adjusted sequentially, so that the larger number to sink , smaller upward. That is, each time a comparison of two adjacent numbers finds that they are in the opposite order of order, they are interchanged.
Algorithm implementation: (HDU 1040 pro-Test AC)
#include <iostream>using namespacestd;Const intN =1005;voidBubblesort (intA[],int );voidPrintintA[],intnum);voidSwapint&a,int&b);intMain () {intS[n]; intT; CIN>>u; while(t--) { intN; CIN>>N; for(intj=0; j<n;j++) Cin>>S[j]; Bubblesort (S,n); Print (s,n); cout<<Endl; } return 0;}voidBubblesort (intA[],intNum//Bubble Sort Algorithm{ for(intI=0; i<num-1; i++) { for(intj=0; j<num-i-1; j + +) { if(a[j]>a[j+1]) {Swap (A[j],a[j+1]); } } }}voidSwapint&a,int& B)//Interchange Element{ inttemp; Temp=A; A=b; b=temp;}voidPrintintA[],intN//Output array elements{cout<<a[0]; for(intk=1; k<n;k++) {cout<<" "<<A[k]; }}
View Code
n Number of orders compared to the number of n-1 times
Algorithm time complexity: O (n2)
Space complexity: O (N)
Improved version:
The above bubble sort in the sort operation can only find a maximum or minimum value, but you can get two maximum values at a time if you make a forward and reverse two-pass bubbling method in each order.(the largest and smallest ), thus reducing the number of sort trips by almost half.
voidBubblesort_modify (intA[],intNum//Bubble Sort Algorithm{ intlow=0; inthigh=num-1; while(low<High ) { for(inti=low;i//forward bubbling to get maximum value if(a[i]>a[i+1]) Swap (A[i],a[i+1]); High--;//High move forward one for(inti=high;i>low;i--)//reverse bubbling to get the minimum value { if(a[i]<a[i-1]) Swap (A[i],a[i-1]); } Low++;//Low to move back one }}
Eight sort algorithm five--exchange sort-bubble sort (Bubble sort)