Java 快速排序对除少数项目外的所有项目进行排序
我花了很多时间试图找出我没有权利的东西;除了我之外,调试和其他一切似乎都无法解释为什么我的快速排序遗漏了一些排序项目 我复制了下面的排序和分区代码。我有一种感觉,这是一件非常明显的事情,我看得太多了,但我花了无数时间调试、研究和重写我的代码,结果总是一样的Java 快速排序对除少数项目外的所有项目进行排序,java,quicksort,Java,Quicksort,我花了很多时间试图找出我没有权利的东西;除了我之外,调试和其他一切似乎都无法解释为什么我的快速排序遗漏了一些排序项目 我复制了下面的排序和分区代码。我有一种感觉,这是一件非常明显的事情,我看得太多了,但我花了无数时间调试、研究和重写我的代码,结果总是一样的 // quicksort the subarray from a[lo] to a[hi] private void sort(Comparable[] a, int lo, int hi) { if((hi-lo)>1){
// quicksort the subarray from a[lo] to a[hi]
private void sort(Comparable[] a, int lo, int hi) {
if((hi-lo)>1){
int pivot = partition(a,lo,hi);
sort(a,lo,pivot);
sort(a,pivot+1,hi);
}
}
// partition the subarray a[lo .. hi] by returning an index j
// so that a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
private int partition(Comparable[] a, int lo, int hi) {
//find middle
int pivotIndex = (hi+lo)/2;
//pick pivot
Comparable pivot = a[pivotIndex];
//create left and right pointers
int left = lo, right = hi;
//start comparing
//compare until left passes right
while(left<right){
//while left is less than pivot move on
while(a[left].compareTo(pivot) < 0) left++;
//while right is greater than pivot move on
while(a[right].compareTo(pivot) > 0) right--;
//if the pointers have passed each other we're done
//if a[left] is greater than a[right] swap them
if(a[left].compareTo(a[right]) > 0){
Comparable holder = a[left];
a[left] = a[right];
a[right] = holder;
//increment/decrement
left++; right--;
}
}
return right;
}
//将子阵列从[lo]快速排序到[hi]
私有无效排序(可比[]a,整数低,整数高){
如果((高-低)>1){
int pivot=分区(a、lo、hi);
排序(a、lo、枢轴);
排序(a,枢轴+1,hi);
}
}
//通过返回索引j对子阵列a[lo..hi]进行分区
//因此,a[lo..j-1]只需删除left++;对--代码>,一切都会好起来。@GrzegorzKaczan很确定不是这样。我自己还没有发现这个bug,但是我运行了一个测试用例排序Character[]s={'z','y','x','a','b','c','w','v','u'
并删除左++;对--代码>未更正问题。非常奇怪。。我又想了一下,我猜递归调用出了问题。但我不能直接看到故障。只需看一下的实现(与您的实现非常类似),但递归或多或少在分区部分内部进行。