【问题标题】:QUICKSORT : how to resolve java.lang.StackOverflowError?QUICKSORT:如何解决 java.lang.StackOverflowError?
【发布时间】:2013-07-08 14:54:45
【问题描述】:

我正在编写一个快速排序程序,以在 100000 的输入大小上运行。我尝试以 500 的大小运行它,它工作正常,但有数百万个输入,程序会因以下错误代码而中断

“java.lang.StackOverflowError”

有人可以帮我解决这个问题吗?我很确定我没有陷入无限递归。有一个基本情况会导致递归方法返回。

public class count_comparisons {

    public static int count_comp =0;
    public static int partitioning(int[] A, int lo, int hi) {

        int pivot = A[lo];

        int i=lo+1;
        int j=lo+1;
        int k=lo;

        for ( j=lo+1;j<=hi;j++) {            
            if (A[j] < pivot) {
                swap(A,i,j);
                i++;
            }
        }
        swap(A,i-1,lo);        
        return i-1;
    }

    public static int quicksort(int[] A, int lo, int hi) {
        if (lo>=hi) return 0;
        int pivot = partitioning(A,lo,hi);

        //StdOut.println("Pivot index is "+ pivot +" and entry at pivot is " + A[pivot]);

        StdOut.println("Lo is "+ lo +" and Hi is " + hi);
        int h = quicksort(A,lo,pivot-1);
        int m = quicksort(A,pivot+1,hi);
        //StdOut.println("First half count is "+h);
        //StdOut.println("Second half count is "+m);
        count_comp = count_comp + h + m;
        return (hi-lo);
    }

    public static void quicksort(int[] A,int N) {  
        int k = quicksort(A,0,N-1);
        count_comp = count_comp + k;
        //StdOut.println(" First count is "+k);
    }

    private static void swap(int[] A, int j,int k) {
        int temp = A[j];
        A[j] = A[k];
        A[k] = temp;
    }

    public static void main(String[] args) {
        In in = new In("input_file.txt"); 
        int N=569;
        int[] A = new int[569];
        int i=0;
        while (!in.isEmpty()) {
            A[i++] = in.readInt();
        }
        count_comparisons.quicksort(A,N);

        for( int h=0;h<N;h++) {}
            //StdOut.print(A[h]);
        StdOut.println();
        StdOut.println(count_comparisons.count_comp);

    }
}

【问题讨论】:

标签: java recursion stack-overflow


【解决方案1】:

递归不需要是无限的以导致堆栈溢出:它只需要足够长以溢出堆栈。

快速排序可能非常慢:在某些特别不幸的情况下,可能需要多达 n-1 调用,最坏情况下的性能为 O(n^2)

您有两种选择 - 通过使用显式堆栈数据结构或通过增加 JVM 分配给程序线程的堆栈大小来重写代码而不递归。

【讨论】:

  • @Alnitak Collections#sort 的实现是归并排序,不是快速排序=\
【解决方案2】:

尾递归消除有一个技巧,它只递归到较小的子集,这限制了递归深度。

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多