The so-called bubble algorithm is to think of the sort of water blisters, small on top, big in the bottom
The adjacent two elements are compared, if the front is larger than the back, it is exchanged.
If there is a set of data: 3,6,2,1,9
->3,2,1,6,9
->2,1,3,6,9
->1,2,3,6,9
int main () {int a[] = {3,6,2,1,9};for (int i = 0; i < sizeof (a)/4; i++) {for (int j = 0; J < sizeof (a)/4-i-1; j + +) {if (a[j]>a[j + 1]) {int temp = A[j];a[j] = a[j + 1];a[j + 1] = temp;}}} for (int i = 0; i < sizeof (a)/4; i++) {printf ("%d ", A[i]);} Cin.get ();}
Time complexity: If it is already lined up, the record moves to N-1, the mobile data is 0, the best complexity is O (N), and if the file is reversed (worst) sorted to N-1 times, each
Sorting requires a N-1 comparison and three data exchange. The complexity is O (N2). The spatial complexity of O (1) bubble sort is a stable sort.
Optimization:
You can add a flag bit and set the tag to flase if the data has been exchanged. If the tag is always ture, there is no data exchanged,
int main () {int a[] = {3,6,2,1,9}; bool flage = true;for (int i = 0; i < sizeof (a)/4; i++) {for (int j = 0; J < sizeof (a)/4-i-1; j + +) { if (A[j]>a[j + 1]) {int temp = A[j];a[j] = a[j + 1];a[j + 1] = temp; Flage = false;}} if (flage) break ;} for (int i = 0; i < sizeof (a)/4; i++) {printf ("%d ", A[i]);} Cin.get ();}
Algorithm one: Bubbling algorithm