When we are learning C language, we have learned bubble sorting. Please refer to "children learn C language (26): bubble sorting": https://www.jianshu.com/p/587ff823ba5b
Chapter 9 of datastructure of Dahua talks about an optimized bubble sorting. The complete code is as follows:
#include<iostream> using namespace std; #define MAX 5 typedef struct { int r[MAX + 1]; int len; }seq; void myswap(seq *x, int i, int j) { int temp = x->r[i]; x->r[i] = x->r[j]; x->r[j] = temp; } void bubbleSort(seq *x) { bool flag = true; // i represents the round of comparison, not the array subscript for (int i = 1; i < x->len && flag; i++) { cout << "The first" << i << "Wheel sorting:"; flag = false; // j represents array subscript. Here is the comparison from back to front, which can move multiple at the same time, improving efficiency // For example, {3, 2, 1, 5, 4} becomes {1, 3, 2, 4, 5} after a round of comparison for (int j = x->len - 1; j >= i; j--) { if (x->r[j] > x->r[j + 1]) { myswap(x, j, j + 1); flag = true; } } for(int i = 1; i <= x->len; i++) { cout << x->r[i] << ' '; } cout << endl; } } int main() { cout << "input data:"; seq s; for(int i = 1; i <= MAX; i++) { cin >> s.r[i]; } s.len = MAX; bubbleSort(&s); cout << "Sorting results:"; for(int i = 1; i <= s.len; i++) { cout << s.r[i] << ' '; } cout << endl; return 0; }
Operation result:
Input data: 3 2 1 5 4 Round 1: 1 3 2 4 5 Round 2: 1 2 3 4 5 Round 3: 1 2 3 4 5 Sorting result: 1 2 3 4 5
Join the children's informatics osseq QQ group, please sweep the left two dimensional code, pay attention to the WeChat public number, please sweep the right two-dimensional code.