使用java合并排序recusrion错误的问题

凯蒂001

我正在关注使用 java 的合并排序算法的 youtube 视频教程。

但我不断收到此错误:

Exception in thread "main" java.lang.StackOverflowError 
        at merge_sort.msort(merge_sort.java:27) 

我的代码:

public static int[] msort(int a[])
    {
        int n = a.length;
        int m = n / 2;
        int l[] = new int[m];
        int r[];
        if(n % 2 == 0) 
        {
            r = new int[m];
        }
        else
        {
            r = new int[m+1];
        }
        for(int i = 0; i < m; i++)
        {
            l[i] = a[i];
        }
        for(int j = 0; j < r.length; j++)
        {  
           r[j] = a[m+j];
        }
        int res[] = new int[n];
        l = msort(l);
        r = msort(r);
        res = merge(l, r);
        return res;
    }
    public static int[] merge(int l[], int r[])
    {
        int len = l.length + r.length;
        int res[] = new int[len];
        int lp = 0, rp = 0, resp = 0;
        while(lp < l.length || rp < r.length)
        {
            if(lp < l.length && rp < r.length)
            {
                if(l[lp] < r[rp])
                {
                    res[resp++] = l[lp++];
                }
                else
                {
                    res[resp++] = r[rp++];
                }
            }
            else if(lp < l.length)
            {
                res[rp++] = l[lp++]; 
            }
            else if(rp < r.length)
            {
                res[rp++] = r[rp++]; 
            }
        }
        return res;
    }

谁能帮我解决这个问题?谢谢

首先,您缺少停止条件。如果要排序的数组长度 < 2,则应停止递归:

public static int[] msort(int a[])
{
    if (a.length < 2) { // add this condition
        return a;
    }

    ...
}

其次,您在两个数组索引中有一个错字:

        else if(lp < l.length)
        {
            res[rp++] = l[lp++]; 
        }
        else if(rp < r.length)
        {
            res[rp++] = r[rp++]; 
        }

应该

        else if(lp < l.length)
        {
            res[resp++] = l[lp++]; 
        }
        else if(rp < r.length)
        {
            res[resp++] = r[rp++]; 
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章