Java 快速排序未正确排序
我基本上是从加州大学伯克利分校的一个快速排序视频中复制了我的代码,但它几乎只能成对排序。我不知道这里发生了什么 每一行我都看了好几遍,看不出有什么不对。一切对我都有意义Java 快速排序未正确排序,java,sorting,quicksort,Java,Sorting,Quicksort,我基本上是从加州大学伯克利分校的一个快速排序视频中复制了我的代码,但它几乎只能成对排序。我不知道这里发生了什么 每一行我都看了好几遍,看不出有什么不对。一切对我都有意义 static <E extends Comparable<? super E>> void quicksort(E[] A, int low, int high) { if (low < high) { int pivotIndex = (low + high) / 2;
static <E extends Comparable<? super E>>
void quicksort(E[] A, int low, int high) {
if (low < high) {
int pivotIndex = (low + high) / 2;
E pivot = A[pivotIndex];
// move pivot to end
A[pivotIndex] = A[high];
A[high] = pivot;
int i = low - 1;
int j = high;
do {
do {
i++;
} while (A[i].compareTo(pivot) < 0);
do {
j--;
} while ((A[i].compareTo(pivot)) > 0 && (j > low));
if (i < j) {
E swap = A[i];
A[i] = A[j];
A[j] = swap;
}
} while (i < j);
// i is now the first spot in the right partition (where we will put pivot)
// now put pivot back where it belongs
A[high] = A[i];
A[i] = pivot;
quicksort(A, low, i - 1); // sort left partition
quicksort(A, i + 1, high);
}
}
static第二个内部循环中的比较使用[i]进行比较,而它应该使用[j]:
} while ((A[j].compareTo(pivot)) > 0 && (j > low)); // A[j] not A[i]
这种类型的快速排序的另一种变体不是将枢轴与[HIGH ]交换,而是通过将枢轴放在中间,代码不必在第二内环中检查J>低,这有点快。使用此变体需要其他更改:init j到high+1,两个递归调用应该是快速排序(A,low,j)和快速排序(A,j+1,high)。请注意,与pivot相等的值(包括pivot本身)可能会在任一分区中结束,因为与pivot相等的值会被交换
原语(int)的示例代码,在较小或相等的部分上使用递归,然后在较大的部分上迭代,以避免最坏情况下的堆栈溢出。它可以转换为使用通用对象E
public static void qsort(int[] a, int lo, int hi)
{
while(lo < hi){
int md = lo+(hi-lo)/2;
int ll = lo-1;
int hh = hi+1;
int p = a[md];
int t;
while(true){
while(a[++ll] < p);
while(a[--hh] > p);
if(ll >= hh)
break;
t = a[ll];
a[ll] = a[hh];
a[hh] = t;
}
ll = hh++;
if((ll - lo) <= (hi - hh)){
qsort(a, lo, ll);
lo = hh;
} else {
qsort(a, hh, hi);
hi = ll;
}
}
}
publicstaticvoidqsort(int[]a,int-lo,int-hi)
{
while(lop);
如果(ll>=hh)
打破
t=a[ll];
a[ll]=a[hh];
a[hh]=t;
}
ll=hh++;
如果((ll-lo)谢谢你的回答!你的方法也有道理,但是你知道我的代码为什么不工作吗?这对我来说同样有道理。@ellesummer-问题不在于将轴交换到[high],而是在应该使用[j]时使用[i]进行比较的第二个内部循环为了比较。我更新了我的答案。我不知道是否还有其他问题,因为如果某个具体实现中存在一些微妙的问题,那么查找快速排序失败案例可能会很困难。非常感谢。我完全没有注意到这一点。