基本快排

快排

public class QuickSort {
    public static void sort(Comparable[] array) {
        sort(array, 0, array.length - 1);
    }

    public static void sort(Comparable[] array, int low, int high) {
        if (low >= high) {
            return;
        }
        int i = low + 1;
        int j = high;

        Comparable target = array[low];
        while (true) {
            while (i < high && array[i].compareTo(target) < 0) {
                i++;
            }
            while (j > low && array[j].compareTo(target) > 0) {
                j--;
            }

            if (i < j)
                swap(array, i, j);
            else
                break;
        }

        swap(array, low, j);
        sort(array, low, j - 1);
        sort(array, j + 1, high);
    }

    public static void swap(Comparable[] array, int a, int b) {
        Comparable tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
    }

    public static void main(String[] args) {
        Integer[] array = { 2, 5, 4, 5, 6, 10, 3 };
        QuickSort.sort(array);
        for (Integer i : array) {
            System.out.print(i + " ");
        }
    }
}

猜你喜欢

转载自dugu108.iteye.com/blog/1772092