如何解决我实现了一个QuickSort算法,该算法仅适用于7个元素,然后给出了8个或更多元素的StackOverflow错误
我实现了一个QuickSort算法,该算法仅适用于7个元素,然后给出了8个或更多元素的StackOverflow错误。进入无限循环。对于数组中存在的元素数量工作正常,但是如果我再添加一个元素,它将返回StackOverflow错误 这是我的代码:
public class QuickSort
{
public void main()
{
QuickSort o = new QuickSort();
int arr[] = {8,5,2,10,1,7,3};
o.sort(arr,arr.length-1);
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
void sort(int []arr,int l,int h)
{
if(l<h)
{
int pi = partition(arr,l,h);
sort(arr,pi);
sort(arr,pi+1,h);
}
}
int partition(int arr[],int h)
{
int pivot = arr[l];
int i=l,j=h;
while(i<j)
{
while(arr[i]<=pivot)
{
i++;
}
while(arr[j]>pivot)
{
j--;
}
if(i<j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
int t = arr[j];
arr[j] = pivot;
arr[l] = t;
return j;
}
}
解决方法
我相信问题是您没有将支点放在正确的位置。
这是您的代码,但有一点改动:
int partition(int arr[],int l,int h){
int pivot = arr[l];
int i= l,j=h;
while(i < j){
while( i < j && arr[i]<=pivot){ i++;}
while( i < j && arr[j]>pivot){ j--;}
if(i< j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
//here it is determined where the pivot should go. It is easiest to understand with an example
//after the loop arr can be 3 1 2 4 5
//the pivot being 3 should be switched with the number 2 but index j sometimes points to number 2 and sometimes to number 4
//the following code determines the desired index
int lowerInd = arr[j] <= pivot ? j : j - 1;
int t = arr[lowerInd];
arr[lowerInd] = arr[l];
arr[l] = t;
return lowerInd;
}
此外,在您的排序方法中,调用sort(arr,l,pi - 1);
而不是sort(arr,pi);
void sort(int[] arr,int h){
if(l<h){
int pi = partition(arr,h);
sort(arr,pi - 1);
sort(arr,pi+1,h);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。