正如标题所暗示的,我目前正致力于快速排序的Java实现。我在我的算法教科书(Sedgewick文本)中读到,选择随机数据透镜可以减少在数组已经排序时我会遇到更糟糕的案例性能的可能性。当我使用第一个元素(一直到左边)作为枢轴时,我一直收到一个排序数组。然而,当我选择一个随机的枢轴时,我开始得到未分类的废话。谁能告诉我我犯的错误?提前谢谢。
static void quickSort(String arr[], int left, int right) {
if (left < right) {
int index = partition(arr, left, right);
quickSort(arr, left, index - 1);
quickSort(arr, index + 1, right);
}
}
static int partition(String[] a, int p, int r) {
Random rand = new Random();
int randomNumber = rand.nextInt(a.length);
String pivot = a[randomNumber];
int left = p - 1; // i is index into left side
// The following for loop maintains these conditions
// 1. Every element of a[p..i] is less than or equal to the pivot.
// 2. Every element of a[i+1..j-1] is greater than the pivot.
// 3. a[r] equals the pivot.
for (int j = p; j < r; j++) { // j is index into right side
// Find out which side a[j] goes into. If the left side, then we
// have
// to increment the size of the left side and then get a[j] into
// position i.
// If the right side, a[j] is already where we want it, so just
// incrementing
// j in the loop header suffices.
if (a[j].compareTo(pivot) <= 0) {
left++; // a[j] belongs in the left side, so we make it one
// larger
swap(a, left, j);
}
}
// We dropped out of the loop because j == r. Every element of a[p..i]
// is less than or equal to the pivot, and every element of a[i+1..r-1]
// is
// greater than the pivot. If we put the pivot into position i+1, then
// we
// have what we want: a[p..i] is less than or equal to the pivot, a[i+1]
// equals the pivot, and a[i+2..r] is greater than the pivot.
swap(a, left + 1, r);
// Return the index of where the pivot ended up.
return left + 1;
}
// Swap the elements at two indices i and j in array a.
static void swap(String[] a, int i, int j) {
String t = a[i];
a[i] = a[j];
a[j] = t;
}
答案 0 :(得分:3)
您正在从整个数组中随机选择枢轴,它应该是您在其上调用分区的子列表的元素:
int randomNumber = p+rand.nextInt(r-p);
String pivot = a[randomNumber];
选择枢轴后,应将其与子列表的第一个或最后一个元素交换。这样可以更容易地编写分区算法。