- simple but inefficient
- Scan the data from left to right, select the largest data, put it on the right
- Key point: Compare two adjacent numbers and swap if the number on the left is greater than the number on the right
- Assuming that there are n elements waiting to be compared in the array, when the first sorting is over, the largest element will be moved to the end of the sequence; when the second sorting is over, the second largest element will be moved to the n- of the sequence. 1 position; after n-1 sorting, the bubble sorting is completed~
The C implementation is as follows: requires 2 loops
One trip: 1 with 2, 2 with 3, 3 with 4, 4 with 5, 5 with 6, 6 with 7, 7 with 8, 8 with 9, 9 with 10: the back is higher than the front, and the bottom is lower than the front. No transposition - swap the largest to the right for a total of 9 comparisons
2 times: 1 with 2, 2 with 3, 3 with 4, 4 with 5, 5 with 6, 6 with 7, 7 with 8, 8 with 9: the back is higher than the front, and the bottom is lower than the front, no transposition— ——Change the next largest to n-1 bit for a total of 8 comparisons
So ~ every time the outer loop is completed, the number of comparisons in the inner loop is reduced by one
#include<stdlib.h> #include<stdio.h> void bubblesort(int *a, int n); intmain() { int k; int a[10] = {2,4,6,8,0,1,3,5,7,9}; bubblesort(a, 10); for (k = 0; k < 10; k++) printf("%d\t", a[k]); system("pause"); return 0; } void bubblesort(int *a,int n) { int i, j, t; //10 color bars, 9 rounds of comparison, the outer loop controls the number of rounds of comparison for (i = 0; i < n - 1; i++) { //Every time the outer loop is performed once, the comparison of the inner loop is reduced once, so j<ni-1 for (j = 0; j < n - i - 1; j++) { if (a[j]>a[j + 1]) { t = a[j ]; a[j] = a[j + 1]; a[j + 1] = t; } } } }