鸡尾酒排序

这个排序名字很多,又叫摇晃排序,双向冒泡排序等(见维基),是冒泡排序的一个改进。效率会好一点,但还是差不多。

冒泡排序每次向一个方向冒一个泡,而这个每次向后冒泡后再向前冒泡。

我对这种写法比较有兴趣,不断压缩“数组长度”直至有序或为1.

public static void shakerSort(int[] A){
    boolean unsorted = true;
    int top = A.length-1;
    int bottom = 0;
    while(unsorted){
        unsorted = false;
        for(int i = bottom; i < top; i ++){
            if(A[i] > A[i+1]){
                swap(A, i, i+1);
                unsorted = true;
            }
        }
        top --;
        for(int i = top; i > bottom; i --){
            if(A[i] < A[i-1]){
                swap(A, i, i-1);
                unsorted = true;
            }
        }
        bottom ++;
    }
}
Java
原文地址:https://www.cnblogs.com/7hat/p/3381351.html