简体   繁体   中英

Recursive Mergesort in Java

first and foremost, thanks in advance for any and all replies, they are greatly appreciated. Now to the purpose of this post; I am having trouble implementing a merge sort in Java. I am getting a Null Pointer Exception, however, I can not figure out what the mistake is, to me the code looks ok. Here is what I have thus far:

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;


}

...apparently, the pointer exception is coming from the 'For' statements in the 'mSort' methods, anything that can point out my mistake or guide me in the right direction is greatly appreciated!!!

left and right are null, you can't add to that!!!

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

must be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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