我实现了一个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);
  }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...