1. 冒泡排序簡介(默認從小到大排序)
核心思想:只比較相鄰的兩個元素,如果滿足條件就交換
5 8 2 1 6 9 4 3 7 0
目標:0 1 2 3 4 5 6 7 8 9
第一次排序:
5 < 8 不交換
5 8 2 1 6 9 4 3 7 0
8 >2 滿足條件 交換....
5 2 8 1 6 9 4 3 7 0
5 2 1 8 6 9 4 3 7 0
5 2 1 6 8 9 4 3 7 0
5 2 1 6 8 9 4 3 7 0
5 2 1 6 8 4 9 3 7 0
5 2 1 6 8 4 3 9 7 0
5 2 1 6 8 4 3 7 9 0
5 2 1 6 8 4 3 7 0 9
下一次交換
2 5 1 6 8 4 3 7 0 9
2 1 5 6 8 4 3 7 0 9
2 1 5 6 8 4 3 7 0 9
2 1 5 6 8 4 3 7 0 9
2 1 5 6 4 8 3 7 0 9
2 1 5 6 4 3 8 7 0 9
2 1 5 6 4 3 7 8 0 9
2 1 5 6 4 3 7 0 8 9
下一次交換
1 2 5 6 4 3 7 0 8 9
1 2 5 6 4 3 7 0 8 9
1 2 5 6 4 3 7 0 8 9
1 2 5 4 6 3 7 0 8 9
1 2 5 4 3 6 7 0 8 9
1 2 5 4 3 6 7 0 8 9
1 2 5 4 3 6 0 7 8 9
下一次交換
1 2 5 4 3 6 0 7 8 9
1 2 5 4 3 6 0 7 8 9
1 2 4 5 3 6 0 7 8 9
1 2 4 3 5 6 0 7 8 9
1 2 4 3 5 6 0 7 8 9
1 2 4 3 5 0 6 7 8 9
下一次交換
1 2 4 3 5 0 6 7 8 9
1 2 4 3 5 0 6 7 8 9
1 2 3 4 5 0 6 7 8 9
1 2 3 4 5 0 6 7 8 9
1 2 3 4 0 5 6 7 8 9
下一次交換
1 2 3 4 0 5 6 7 8 9
1 2 3 4 0 5 6 7 8 9
1 2 3 4 0 5 6 7 8 9
1 2 3 0 4 5 6 7 8 9
下一次交換
1 2 3 0 4 5 6 7 8 9
1 2 3 0 4 5 6 7 8 9
1 2 0 3 4 5 6 7 8 9
下一次交換
1 2 0 3 4 5 6 7 8 9
1 0 2 3 4 5 6 7 8 9
下一次交換
0 1 2 3 4 5 6 7 8 9
2. 總共進行了 n-1次大的交換(n個元素 只有1個元素不需要排序)
5 2 1 6 8 4 3 7 0 9 //這次交換 一共變化了9次
2 1 5 6 4 3 7 0 8 9 // 8次
1 2 5 4 3 6 0 7 8 9
1 2 4 3 5 0 6 7 8 9
1 2 3 4 0 5 6 7 8 9
1 2 3 0 4 5 6 7 8 9
1 2 0 3 4 5 6 7 8 9
1 0 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
每一次小交換是9 8 7 6 5 4 3 2 1 次交換,也就是說
for(int i = 0;i < N-1;i++){ for(int j = 0;j < N-1-i;i++){ 交換 ... } }
3. 實戰 for while do-while 遞歸
#include<stdio.h> #include<stdlib.h> #define N 10 void print(int *a){ for (int i = 0; i < N; i++) { printf("%d ",*(a+i)); } printf("\n"); } void maopao_for(int *a){ 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; } } print(a); } } void maopao_while(int *a) { int i = 0; while (i < N - 1) { int j = 0; while (j < N - 1 - i) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } j++; } print(a); i++; } } void maopao_do_while(int *a) { int i = 0; do{ int j = 0; do{ if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } j++; } while (j < N - 1 - i); print(a); i++; } while (i < N - 1); } // 遞歸可以減少一次循環 void maopao_digui(int *a,int count) { if(count>=N) return ; for (int j = 0; j < N - 1 - count; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } }//printf("下一次交換\n\n\n"); print(a); maopao_digui(a,count+1); } int main(){ int a[N] = {5,8,2,1,6,9,4,3,7,0}; printf("排序前:\n"); print(a); printf("排序中:\n"); maopao_digui(a,0); printf("排序后:\n"); print(a); return 0; }