简体   繁体   English

Java堆栈溢出错误?

[英]java stack overflow error?

Exception in thread "main" java.lang.StackOverflowError
at Search.mergeSort(Search.java:41)
at Search.mergeSort(Search.java:43)
at Search.mergeSort(Search.java:43)
at Search.mergeSort(Search.java:43)
at Search.mergeSort(Search.java:43)

I keep getting this error when I try to run my program. 当我尝试运行程序时,我一直收到此错误。 My program is supposed to take string input from a file and sort it using this algorithm. 我的程序应该从文件中获取字符串输入,然后使用此算法对其进行排序。 Any ideas? 有任何想法吗? Problematic lines from code: 代码中有问题的行:

public static void mergeSort(String[] word, int p, int r){
int q;
if(p<r){
q=p+r/2;
mergeSort(word,p,q);
mergeSort(word, q+1,r);
merge(word, p, q, r);
}
}

EDIT 编辑

These two functions sort the String array by dividing the array in half, sorting each half separately, and merging them together. 这两个函数通过将String数组分成两半,分别对每一半进行排序并将它们合并在一起来对String数组进行排序。 Int q is the halfway point, and the arrays being evaluated are from word[p] to word[q] and word[q+1] to word[r]. Int q是中点,要评估的数组是从word [p]到word [q]和word [q + 1]到word [r]。 here's merge function: 这是合并功能:

public static void merge(String[] word, int p, int q, int r){
    int n1 = q-p+1;
    int n2 = r-q;
    String[] L = new String[n1];
    String[] R = new String[n2];
    int i, j, k;

    for(i=0; i<n1; i++) L[i] = word[p+i];
    for(j=0; j<n2; j++) R[j] = word[q+r+1];
    i=0; j=0;
    for(k=p; k<=r; k++){
        if(i<n1 && j<n2){
            if(L[i].compareTo(R[j])<0){
                word[k] = L[i];
                i++;
            }else{
                word[k] = R[j];
                j++;
            }
        }else if(i<n1){
            word[k] = L[i];
            i++;
        }else if(j<n2){
            word[k] = R[j];
            j++;
        }
    }

Walk through with a debugger. 逐步调试。 You'll see exactly how it's leading to an infinite recursion. 您将确切看到它如何导致无限递归。 IDEs (Eclipse, IntelliJ) have them built in. IDE(Eclipse,IntelliJ)已内置它们。

The problem is that your calculation of q is incorrect. 问题是您对q的计算不正确。 It is supposed to be the halfway point between p and r , and the way to calculate that is: 它应该是pr之间的中间点,计算方法是:

 q = p + (r - p) / 2;

or 要么

 q = (p + r) / 2;

But you've written: 但是你写了:

 q = p + r / 2;

which is equivalent to 相当于

 q = p + (r / 2);

When making recursive methods, you need some base case, otherwise you'll get infinite recursion like you are right now. 进行递归方法时,您需要一些基本情况,否则您将像现在一样获得无限递归。

In your mergeSort method, you don't have a base case . 在您的mergeSort方法中, 您没有基本情况 You need to put a check in to see if the part you're sorting is already sorted; 您需要检查一下要分类的零件是否已经被分类。 if word[p..r] is sorted, then you should not call mergeSort 如果对word[p..r]进行了排序,则不应调用mergeSort

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

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