101.png

    1. /*
    2. 双向冒泡排序:
    3. 所谓双向,即两个方向同时进行排序操作,可以在一定程度上降低时间开销。
    4. 从左向右大值往下沉,从右往左小值往上冒,只需要的遍历次数为元素个数的一半
    5. */
    6. #include <stdio.h>
    7. #include <stdlib.h>
    8. void swap(int &a, int &b) {
    9. int tmp;
    10. tmp = a;
    11. a = b;
    12. b = tmp;
    13. }
    14. void BibubbleSort(int *arr, int len) {
    15. int low = 0, high = len - 1;
    16. int flag = 1;
    17. while (low < high && flag) {//循环条件
    18. flag = 0;//标志本轮是否有操作
    19. for (int j = low; j < high; j++) {//往下沉
    20. if (arr[j] > arr[j + 1]) {//逆序则交换
    21. swap(arr[j], arr[j + 1]);
    22. flag = 1;
    23. }
    24. }
    25. high--;
    26. for (int j = high; j > low; j--) {//往上冒
    27. if (arr[j] < arr[j - 1]) {//逆序则交换
    28. swap(arr[j], arr[j - 1]);
    29. flag = 1;
    30. }
    31. }
    32. low++;
    33. }
    34. }
    35. int main() {
    36. int arr[] = { 9,3,4,10,8,5,7,12,10,15 };
    37. BibubbleSort(arr, 10);
    38. return 0;
    39. }