【问题标题】:I implemented a QuickSort Algorithm which only works for 7 elements and then gives a StackOverflow Error for 8 elements or more我实现了一个 QuickSort 算法,它只适用于 7 个元素,然后对 8 个或更多元素给出 StackOverflow 错误
【发布时间】:2020-12-06 11:18:22
【问题描述】:

我实现了一个 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,0,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,l,pi);
        sort(arr,pi+1,h);
    }
}

int partition(int arr[],int l,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;
}
}

【问题讨论】:

  • 在第一次分区调用开始时,你的 l==0 和 h==6 你在最后(仍然是 6)返回 j 并将其用作下一次调用的 h再次与 l==0 一起分区,因此结果仍然相同。

标签: java arrays algorithm sorting quicksort


【解决方案1】:

我认为问题在于您没有将支点放在正确的位置。

这是您的代码,稍作改动:

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,l,pi);

void sort(int[] arr,int l,int h){
  if(l<h){            
      int pi = partition(arr,l,h);
      sort(arr,l,pi - 1);
      sort(arr,pi+1,h);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2012-03-18
    • 1970-01-01
    • 2019-10-15
    • 2017-09-17
    相关资源
    最近更新 更多