C语言 冒泡排序
冒泡排序的原理:兩個相鄰的數比較大小,將兩個數中較大的數往右邊放,小的往左邊放。
代碼如下
// bubble sort v1int bubble_sort(int *array, int len) {int i, j;int temp, loop_count = 0;for (i = 0; i < (len - 1); i++) {for (j = i + 1; j < len; j++) {if (array[i] > array[j]) {temp = array[i];array[i] = array[j];array[j] = temp;}loop_count++;}}printf("loop=%d\n", loop_count);return 0; }// bubble sort v2 int bubble_sort(int *array, int len) {int temp = 0;int i, j, loop_count = 0;int first_diff_flag = 0;for (i = 0; i < len - 1; i++) {if (array[i] > array[i + 1]) {temp = array[i] ;array[i] = array[i + 1];array[i + 1] = temp;if (i >= 1) {if (!first_diff_flag) {j = i;first_diff_flag = 1; // 第1次出現不同值時i賦給j, 退出后array[i]之前的數已排序完成,}i -= 2; // 第i和i + 1個數交換后, 從第i - 1個數開始需要從新比較}} else {if (first_diff_flag) {i = j;first_diff_flag = 0; // 將j賦值給i, 比較array[j]和array[j + 1]}}loop_count++;}printf("loop_count=%d\n", loop_count);return 0; }總結
- 上一篇: 图像处理黑科技—破解文档识别难题(PS检
- 下一篇: 揭开《钢铁侠》AI管家贾维斯神秘面纱的扛