Java中的递归Mergesort

时间:2012-12-08 02:04:44

标签: java implementation mergesort

首先,首先感谢所有回复,我们非常感谢。现在到了这篇文章的目的;我在Java中实现合并排序时遇到问题。我得到一个Null Pointer Exception,但是,我无法弄清楚错误是什么,对我来说代码看起来还不错。以下是我到目前为止的情况:

public List mSort(List l) {

    if (l.size() <= 1)
        return l;

    List left = null;
    List right = null;
    int mid = l.size() / 2;


    for (int x = 0; x < mid; x++)
        left.add(l.get(x));
    for (int x = 0; x >= mid; x++)
        right.add(l.get(x));

    left = mSort(left);
    right = mSort(right);

    return merge(left, right);
}

public List merge(List left, List right) {

    List r = null;
    while (left.size() > 0 || right.size() > 0) {
        if (left.size() > 0 && right.size() > 0)
            if (left.get(0) <= right.get(0)) {
                r.add(left.get(0));
                left.remove(0);
            }
            else {
                r.add(right.get(0));
                right.remove(0);
            }
        else if (left.size() > 0) {
            r.add(left.get(0));
            left.remove(0);

        }
        else if (right.size() > 0) {
            r.add(right.get(0));
            right.remove(0);
        }
    }
    return r;


}

...显然,指针异常来自'mSort'方法中的'For'语句,任何可以指出我的错误或引导我朝正确方向发展的事情都非常感谢!!!

2 个答案:

答案 0 :(得分:1)

leftright为空,您无法添加!!!

List left = new ArrayList();
List right = new ArrayList();

答案 1 :(得分:-1)

for (int x = 0; x < mid; x++)
        left.add(l.get(x));
    for (int x = 0; x >= mid; x++)
        right.add(l.get(x));

必须是

int x = 0;
for (; x < mid; x++)
    left.add(l.get(x));
for (; x < l.size(); x++)
    right.add(l.get(x));