在代码上方运行时,第一个数据透视图返回为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);
}}
答案 0 :(得分:1)
第一次调用QuickSort时,类成员pivot
被赋值为3.然后对QuickSort的递归调用调用quickSortPivot,其结果被分配给pivot
(并且进一步的递归调用也会修改此值)。当对Quicksort的调用返回时,pivot
的值已被修改!
你将declre pivot
作为方法QuickSort
的变量,而不是类QuickSortRevision
的实例变量
PS:函数QuickSort
应该被称为quickSort
答案 1 :(得分:1)
将代码lindex!=hindex
替换为lindex<=hindex
。
因为像lindex > hindex
那样。
像这样的代码:
public class QuickSortRevision{
int pivot;
static int id = 1;
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;
while(lindex <= hindex){
while(arr[lindex]<partition && (lindex<=hindex) ){
lindex++;
}
while(arr[hindex]>partition && (lindex<=hindex) ){
hindex--;
}
System.out.println("low : "+low+" high "+high);
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+" "+arr[lindex]);
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);
}
}