LillianEom
5/12/2018 - 1:53 PM

快速排序的基本算法

分治的排序算法 递归地调用切分进行排序

public class Quick {
//    private static final int M = 5;

    public static void sort(Comparable[] a) {
        // 将所有元素随机排序
//        List<Comparable> list = Arrays.asList(a);
//        Collections.shuffle(list);
//        a = list.toArray(new Comparable[0]);
//        StdRandom.shuffle(a);
        sort(a, 0, a.length - 1);
    }

    private static void sort(Comparable[] a, int low, int high) {
        if (low >= high) {
            return;
        }
        // 改进:对小数组使用插入排序
//        if (high <= low + M) {
//            Insertion.sort(a, low, high);
//            return;
//        }

        int j = partition(a, low, high);
        sort(a, low, j - 1);
        sort(a, j + 1, high);
    }

    private static int partition(Comparable[] a, int low, int high) {
        int i = low, j = high + 1;  // 左右扫描指针
        Comparable v = a[low];      // 切分元素
        while (true) {
            while (less(a[++i], v)) {
                if (i == high) {
                    break;
                }
            }
            while (less(v, a[--j])) {
                if (j == low) {
                    break;
                }
            }
            if (i >= j) {
                break;
            }
            exch(a, i, j);
        }
        exch(a, low, j);
        return j;
    }

    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Integer[] a = {1, 3, 7, 7, 0, 5, 7, 1, 0, 5, 9};
        sort(a);
        show(a);
    }
}