简体   繁体   English

java quicksort堆栈溢出

[英]java quicksort stack overflow

i am still a beginner and i am trying to write a quick sort code 我仍然是初学者,我正在尝试编写快速排序代码

here is my code 这是我的代码

package algo_quicksort;

public class Algo_quicksort {

    public static int partition(int[]A,int p,int r){
        int x=A[p];
        int i=p+1;
        int temp;
        for(int j=p+1;j<r;j++){
            if(A[j]<x){//if A[j] is bigger than the pivot do nothing 
                temp=A[j];
                A[j]=A[i];
                A[i]=temp;
                i++;
            }
        }
        temp=A[p];
        A[p]=A[i-1];
        A[i-1]=temp;
        return i-1;
    }

    public static void quickSort(int[]A,int starPos,int length){
        if(length==1){
            return;
        }
        else{
         if(startPos<length){
        int pivot= partition(A,0,length);
       quickSort(A,startPos,pivot+1);

        quickSort(A, pivot+2,length); 

        }
    }}


    public static void main(String[] args) {
        int a[]={6,5,4,3,2,1};
        System.out.println("A[] after quicksort is: ");

        quickSort(a,0, a.length);
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+"  ");
        }
    }
}

i get a stack over flow exception in the recursive calls 我在递归调用中获得了一个堆栈溢出异常

i do not see why and i would appreciate any help i get ^_^ 我不明白为什么,我会感谢任何帮助我得到^ _ ^

I didn't read it carefully but in 我没有仔细阅读,但在

quickSort(A,0,pivot+1);
quickSort(A, pivot,A.length-pivot);

you definitely over count the element A[pivot] in two branches of your recursive method 你肯定在你的递归方法的两个分支中计算元素A [pivot]

There are many bugs in this program, here are a few that I found: 这个程序有很多错误,这里有一些我发现:

  1. You don't use starPos in quickSort() 你没有在quickSort()使用starPos
  2. You don't use length (you use A.length ) in quickSort() 你不要在quickSort()使用length (你使用A.length quickSort()
  3. The pivot "overlaying" issue that charles mentioned 查尔斯提到的枢纽“重叠”问题
  4. In partition() you should switch places of the item that is right to the pivot and smaller with an item that is left to the pivot and is bigger - you don't do that. partition()你应该切换是该项目的地方right的支点和与被项小left的支点,是更大的-你不这样做。

and there's probably more. 而且可能还有更多。 You can see an implementation I did for quicksort in Ruby (it's easy to migrate it to Java) and compare to your implementation until you get it right - it's trickier than most people think! 你可以看到我在Ruby中为quicksort做的一个实现(很容易将它迁移到Java)并与你的实现进行比较,直到你做对了 - 这比大多数人想象的要复杂!

http://alfasin.com/playing-with-ruby/ http://alfasin.com/playing-with-ruby/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM