我正在尝试实现 RandomizedQuickSort 算法。我认为我正确执行了 randomPartition 方法,但我不知道 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