## 冒泡排序 --- ```c #include<stdio.h> #include<windows.h> #include<stdlib.h> #include<stdbool.h> #define MAXSIZE 21 #define defaultlength 8 int defaultData[3][defaultlength] = { {999,11,22,33,44,55,8,3}, {999,9,3,15,6,66,77,88}, {999,11,88,55,33,66,22,77} }; //默认数组 void Swapen(int* num1, int* num2); int showMainMenu(); void BubbleSort1(int dataHandle[], int n); void BubbleSort2(int dataHandle[], int n); void BubbleSort3(int dataHandle[], int n); /* 设置数组长度为N 1.比较相邻的前后两个数据,如果前面数据大于后面的数据,就将两个数据交换 2.这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第N-1个位置 3.N = N-1,如果N不为0就重复前面两步,否则完成排序 */ int showMainMenu() { int num; printf(" "); printf(" ============================ "); printf(" 冒泡排序的三种实现 "); printf(" ============================ "); int j = 3; while (j > 0) { printf("第%d组数字是: ",4-j); for (int i = 1; i < defaultlength; i++) { printf("%d ", defaultData[j - 1][i]); } printf(" "); j--; } printf("请选择一组数字进行排序:"); scanf_s("%d",&num); } void Swapen(int* num1, int* num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; } //冒泡排序1 void BubbleSort1(int dataHandle[], int n) { int i, j, countTraverse; int timeMove = 0; int timeCompare = 0; for (i = 0; i < n; i++) { for (j = 2; j <= n - i; j++) { timeCompare++; if (dataHandle[j - 1] > dataHandle[j]) { Swapen(&dataHandle[j - 1], &dataHandle[j]); timeMove += 3; for (countTraverse = 1; countTraverse <= n; countTraverse++) { printf("%d ",dataHandle[countTraverse]); } printf(" "); } } } printf("一共比较了%d次。 ", timeCompare); printf("移动的总次数为:%d ", timeMove); } /* 设置一个标志,如果这一趟发生了交换,则为true,否则为false。 明显如果有一趟没有发生交换,说明排序已经完成 */ void BubbleSort2(int dataHandle[], int n) { int j, k, countTraverse; bool flag; int timeMove = 0; int timeCompare = 0; k = n; flag = true; while (flag) { flag = false; for (j = 2; j <= k; j++) { timeCompare++; if (dataHandle[j - 1] > dataHandle[j]) { Swapen(&dataHandle[j - 1], &dataHandle[j]); timeMove += 3; for (countTraverse = 1; countTraverse <= n; countTraverse++) { printf("%d ", dataHandle[countTraverse]); } printf(" "); flag = true; } } k--; } printf("一共比较了%d次。 ", timeCompare); printf("移动的总次数为:%d ", timeMove); } /* 每循环一次会有一个最大值,但是第二次还是会从第一个到n-i个进行比较 如果后面大部分已经确定了顺序,即下一次循环是不是需要到n-i */ void BubbleSort3(int dataHandle[], int n) { int j, k, countTraverse; int flag; int timeMove = 0; int timeCompare = 0; flag = n; while (flag > 0) { k = flag; flag = 0; for (j = 2; j <= k; j++) { timeCompare++; if (dataHandle[j - 1] > dataHandle[j]) { Swapen(&dataHandle[j - 1], &dataHandle[j]); flag = j; timeMove += 3; for (countTraverse = 1; countTraverse <= n; countTraverse++) { printf("%d ", dataHandle[countTraverse]); } printf(" "); } } } printf("一共比较了%d次。 ", timeCompare); printf("移动的总次数为:%d ", timeMove); } int main() { int returnvalue; //如果选择对一段进行排序 使用此变量 system("color f0"); returnvalue = showMainMenu(); system("cls"); //选择判断添加代码 //可以循环,或者单独填写函数名称和传入参数 return 0; } ```