运行上面的代码时,第一个主元返回为 3。该主元在第一个递归方法中作为 2 传输,但在第二个递归中它不采用值 4。有人可以确定问题所在吗?
class QuickSortRevision{
int pivot;
void QuickSort(int[] arr,int low,int high){
if(low>=high)
return;
pivot = quickSortPivot(arr,low,high);//first execution pivot =3
QuickSort(arr,low,pivot-1);//this is taking 0,2 as parameter;
QuickSort(arr,pivot+1,high);//but this is not taking 4,8 as parameter;
}
int quickSortPivot(int[] arr,int low,int high){
int temp,index,partition,lindex,hindex;
lindex=low;
hindex=high-1;
partition = arr[high];
index=high;
System.out.println("low : "+low+" high "+high);
while(lindex!=hindex){
while(arr[lindex]<partition && (lindex!=hindex) ){
lindex++;
}
while(arr[hindex]>partition && (lindex!=hindex) ){
hindex--;
}
if( lindex!=hindex)
{
temp=arr[lindex];
arr[lindex]=arr[hindex];
arr[hindex]=temp;
lindex++;hindex--;
}
}
temp=arr[lindex];
arr[lindex]=partition;
arr[index]=temp;
System.out.println("lindex: "+lindex);
return lindex;
}
void printArray(int[] arr)
{
for(int element : arr)
System.out.print(" "+element);
}
public static void main(String[] args){
QuickSortRevision qs = new QuickSortRevision();
int arr[]={17,41,5,22,54,6,29,3,13};
qs.QuickSort(arr,0,arr.length-1);
qs.printArray(arr);
}}
最佳答案
第一次调用 QuickSort 时,类成员 pivot
被分配值 3。然后,对 QuickSort 的递归调用将调用 fastSortPivot,其结果被分配给 pivot
(并且进一步递归调用也会修改该值)。当对 Quicksort 的调用返回时,pivot
的值已被修改!
您应该将pivot
声明为QuickSort
方法的变量,而不是QuickSortRevision
类的实例变量
PS:函数QuickSort
应该被称为quickSort
关于java - 快速排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37567035/