算法笔记 排序 排序算法 scandi 2025-02-21 2025-04-01 八种排序 三种 O(n ^ 2)的排序:冒泡,选择,插入
三种不基于比较的排序:桶,基数,计数
最后是:归并排序,快速排序
一.冒泡排序 较简单,直接代码注释结合理解即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> using namespace std;int main () { int a[10 ] = { 1 , 10 , 4 , 2 , 3 , 8 , 5 , 9 , 7 , 6 }; int n = 10 ; for (int i = 0 ; i < n - 1 ; i++) { for (int j = 0 ; j < n - 1 - i; 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 < n; i++) cout << a[i] << ' ' ; return 0 ; }
二.选择排序 较简单,直接代码注释结合理解即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <iostream> using namespace std;int main () { int a[10 ] = { 1 , 10 , 4 , 2 , 3 , 8 , 5 , 9 , 7 , 6 }; int n = 10 ; for (int i = 0 ; i < n - 1 ; i++) { int mmin = i; for (int j = i + 1 ; j < n; j++) { if (a[j] < a[mmin]) mmin = j; } if (mmin != i) { int temp = a[i]; a[i] = a[mmin]; a[mmin] = temp; } } for (int i = 0 ; i < n; i++) cout << a[i] << ' ' ; return 0 ; }
三.插入排序 打扑克牌时,当第一张摸到 6,然后第二张摸到 5,会自然的与第一张比较,并把 5 插入到 6 的左边,第三张摸到 8,又把 8 插入到 6 的右边(不同个人习惯,就会有升降序不同的情况)总而言之,这就是插入排序法!下面代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <iostream> using namespace std;int main () { int a[10 ] = { 1 , 10 , 4 , 2 , 3 , 8 , 5 , 9 , 7 , 6 }; int n = 10 ; for (int i = 1 ; i < n; i++) { if (a[i] < a[i - 1 ]) { int temp = a[i]; int j; for (j = i - 1 ; j >= 0 && a[j] > temp; j--) { a[j + 1 ] = a[j]; } a[j + 1 ] = temp; } } for (int i = 0 ; i < n; i++) cout << a[i] << ' ' ; return 0 ; }
四.桶排序 五.基数排序 六.计数排序 七.归并排序 分分—->合合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 #include <iostream> using namespace std;int a[1005 ];int b[1005 ];int n;void bin (int z, int mid, int y) { int q = z, p = mid + 1 ; for (int i = z; i <= y; i++) { if (p > y || (q <= mid && a[q] <= a[p])) { b[i] = a[q++]; } else b[i] = a[p++]; } for (int i = z; i <= y; i++) a[i] = b[i]; } void sot (int z, int y) { if (z == y) return ; int mid = (y + z) / 2 ; sot (z, mid); sot (mid + 1 , y); bin (z, mid, y); } int main () { cin >> n; for (int i = 1 ; i <= n; i++) cin >> a[i]; sot (1 , n); for (int i = 1 ; i <= n; i++) cout << a[i] << ' ' ; return 0 ; }
八.快速排序 找基数,换换换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #include <iostream> using namespace std;int a[1005 ];int n;void sot (int z, int y) { int mid = (z + y) / 2 ; int x = a[mid]; int i = z, j = y; while (i <= j) { while (a[i] < x) i++; while (a[j] > x) j--; if (i <= j) { swap (a[i], a[j]); i++; j--; } } if (z < j) sot (z, j); if (i < y) sot (i, y); } int main () { cin >> n; for (int i = 1 ; i <= n; i++) cin >> a[i]; sot (1 , n); for (int i = 1 ; i <= n; i++) cout << a[i] << ' ' ; return 0 ; }