Basic idea:
The bubble sort is implemented by exchanging two elements, the idea being:
The first trip will be sorted sequence (a[0]~a[n-1]) from the go, 22 adjacent elements to compare, if the latter small, then exchange, compare n-1 times;
At the end of the first trip, the largest element is exchanged to a[n-1] (i.e. sink), and the next order only needs to be done in (a[0]~a[n-2]);
If the element is not swapped in a certain order, the sub-sequence is ordered, then the next order is not made. This method is used for up to n-1 trips.
Bubble Sort Example:
Code:
void Bubblesort (int a[],int n)//bubble Sort {int I, J, Last;i=n-1;while (i>0) {last=0;//up to n-1 trip for (j=0; j<i; j + +)//compare from Go {if (a[j+1]<a[j])//The previous one is larger, swap {swap (a[j],a[j+1]); Last=j;}} i=last;//If there is no interchange element in the order, then last is 0,i 0 jumps out of the loop}}
Improved bubbling algorithm:
The ordering of the maximum and minimum values for forward and reverse. (PS: In fact, some authors will think of the above algorithm as a bubbling Improvement algorithm ~ ~)
void Improvebubblesort (int a[],int N)//improved bubbling {int Low,high,j;low=0;high=n-1;while (Low
time complexity Analysis:Bubble sort is best done in a single trip, n-1 times, so the best case time complexity is O (n), without moving the element, the worst case of n-1 trip, the first I trip compared n-i times, the worst case time complexity is O (n^2).
In addition, the bubbling sort is a stable sorting method after the bubble has been sequenced to finalize the final position of the element.
Resources:
"Data structure" Chen Huinan People's post and telecommunications press
Bubble sort of sorting algorithm