RandomizedQuickSort算法的实现

时间:2013-02-21 02:52:30

标签: algorithm sorting quicksort

我正在尝试实现RandomizedQuickSort算法。我认为我正确地使用了randomizedPartition方法,但我不知道sort方法有什么问题?!

这是我的尝试:

public class RandomizedQuickSort {
    public static void sort(int[] A, int start, int end) {
        if(start < end) {
            int pivot = randomizedPartition(A, start, end);

            sort(A, start, pivot - 1);
            sort(A, pivot + 1, end);
        }
    }

    private static int randomizedPartition(int[] A, int start, int end) {
        int pivot = A[start];
        int pivotIndex = start;

        for(int i = start + 1; i < end; i++) {
            if(A[i] <= pivot) {
                pivotIndex += 1;
                swap(A, pivotIndex, i);
            }
        }
        swap(A, start, pivotIndex);

        return pivotIndex;
    }

    private static void swap(int[] A, int x, int y) {
        int temp = A[x];

        A[x] = A[y];
        A[y] = temp;
    }

    public static void main(String[] args) {
        int A[] = {11, 0, 2, 8, 15, 12, 20, 17, 5, 11, 1, 16, 23, 10, 21, 7, 22, 9};

        sort(A, 0, A.length);

        for(int i = 0; i < A.length; i++) {
            System.out.print(A[i] + ", ");
        }
        System.out.println();
    }
}

这是我得到的输出:

0, 1, 2, 8, 5, 9, 10, 11, 7, 11, 12, 16, 17, 15, 20, 21, 22, 23

1 个答案:

答案 0 :(得分:0)

嗯,除了你没有随机选择一个支点这一事实外,你在对子数组进行排序时会出现一个错误。请注意,您的第一个排序调用是sort(A, 0, A.length),因此结束索引为A.length - 1。因此,第一个子阵列应该最多pivot,而不是pivot - 1。它修复如下:

public static void sort(int[] A, int start, int end) {
    if(start < end) {
        int pivot = randomizedPartition(A, start, end);

        sort(A, start, pivot); // This line needed to be changed!
        sort(A, pivot + 1, end);
    }
}

输出:

0, 1, 2, 5, 7, 8, 9, 10, 11, 11, 12, 15, 16, 17, 20, 21, 22, 23, 
相关问题