试图做Quicksort到位

时间:2014-02-20 02:48:49

标签: java sorting recursion quicksort in-place

似乎它应该非常简单,我之前已经做过快速排序,但我的代码中有一些错误,而且我找不到它。这是我的代码:

public static void quickSortInPlace(ArrayList<Integer> numbers, int left, int right) {
    if(left < right) {
        int index = generatePivot(numbers);
        index = partition(numbers, left, right, index);
        quickSortInPlace(numbers, left, index - 1);
        quickSortInPlace(numbers, index + 1, right);
    }
}

public static int partition(ArrayList<Integer> numbers, int left, int right, int index) {
    int pivot = numbers.get(index);
    int tmp = numbers.get(right);
    numbers.set(right, numbers.get(index));
    numbers.set(index, tmp);
    int newIndex = left;
    for(int i = left; i < right; i++) {
        if(numbers.get(i) <= pivot) {
            tmp = numbers.get(i);
            numbers.set(i, numbers.get(newIndex));
            numbers.set(newIndex, tmp);
            newIndex++;
        }
    }
    tmp = numbers.get(newIndex);
    numbers.set(newIndex, numbers.get(right));
    numbers.set(right, tmp);
    return newIndex;
}

//Chooses an index in the array for the pivot value. Randomly picks 3 values from the array, and chooses the intermediate value. This is simply an optimization.
public static int generatePivot(ArrayList<Integer> numbers) {
    Random rand = new Random();
    int rand1 = rand.nextInt(numbers.size()), rand2 = rand.nextInt(numbers.size()), rand3 = rand.nextInt(numbers.size());
    int pivot1 = numbers.get(rand1), pivot2 = numbers.get(rand2), pivot3 = numbers.get(rand3);
    int max = Math.max(Math.max(pivot1, pivot2), pivot3);
    int min = Math.min(Math.min(pivot1, pivot2), pivot3);
    int pivot = pivot1 ^ pivot2 ^ pivot3 ^ max ^ min;
    int index = 0;
    if(pivot == pivot1) {
        index = rand1;
    } else if(pivot == pivot2) {
        index = rand2;
    } else if(pivot == pivot3) {
        index = rand3;
    }
    return index;
}

我给方法quickSortInPlace一个填充10,000个随机生成的整数的ArrayList,仅仅是为了检查代码的正确性。我希望它能吐出10,000个整数的有序ArrayList。

我现在已经看了45分钟了,所以我确定它是愚蠢的,而我却无法看到它,因为我已经看着这么久。它只是返回完全垃圾。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我还没有完成整个过程,但在我看来,generatePivot并不能保证在左右之间返回一个数字。