0

I am trying to implement the RandomizedQuickSort algorithm. I think that I did the randomizedPartition method correctly but I do not know what is wrong with the sort method?!

Here is my try:

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();
    }
}

Here is the output I got:

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

1 に答える 1

0

ピボットをランダムに選択していないという事実に加えて、サブ配列を並べ替えると、1 つずれているというエラーが発生します。最初の並べ替え呼び出しは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, 
于 2013-02-21T03:02:45.500 に答える