Bubble sort is very easy to understand and implement, with an example from small to large sort:
Set the array length to n.
1. Compared to the next two data, assuming that the previous data is greater than the data behind, the two data exchange.
2. So that the No. 0 data of the array to N-1 data after one traversal, the largest one of the data is "sink" to the N-1 position of the array.
3. N=n-1, assuming that N is not 0, repeat the previous two steps, otherwise the sort is complete.
Very easy to write code according to definition:
Bubble sort 1void BubbleSort1 (int a[], int n) { int i, J; for (i = 0; i < n; i++) for (j = 1; j < N-i; J + +) if (a[j-1] > A[j]) Swap (A[j-1], a[j]);}
The following optimizes it to set a flag that is true if this trip has been exchanged, or false otherwise. It is obvious that a trip did not take place, indicating that the sorting was complete.
Bubble sort 2void BubbleSort2 (int a[], int n) { int J, K; BOOL Flag; k = n; Flag = true; while (flag) { flag = false; for (j = 1; j < K; J + +) if (a[j-1] > A[j]) { Swap (a[j-1], a[j]); Flag = true; } k--;} }
Further optimization is done. Suppose there are 100 numbers of arrays, only the first 10 unordered, the next 90 are all ordered and are larger than the preceding 10 digits, then after the initial traversal, the position of the last interchange must be less than 10, and this position after the data must have been ordered, record this position, The second time only to traverse from the array head to this position is possible.
Bubble sort 3void BubbleSort3 (int a[], int n) {int J, K;int Flag;flag = n;while (Flag > 0) {k = Flag;flag = 0;for (j = 1; J < ; K J + +) if (A[j-1] > A[j]) {Swap (a[j-1], a[j]); flag = J;}}}
After all, bubble sorting is an inefficient sort method that can be used when the data is very small. When data size is larger, it is best to use other sorting methods.
Three implementations of a bubbling sort among the vernacular classic algorithm series