合并在链接列表上排序

时间:2013-04-24 17:30:08

标签: java mergesort

我有作业 - 在java中编写合并排序算法。我使用LinkedList来存储我的数据。我尝试将伪代码从维基百科(http://en.wikipedia.org/wiki/Merge_sort)转换为java,但它不起作用。我不知道为什么,我需要你的帮助。

这是我的MergeSort类。

import java.util.Comparator;

public class MergeSort {
private final Comparator comparator;

public MergeSort(Comparator comparator) {
    this.comparator = comparator;
}

public LinkedList sort(LinkedList list) {
    if(list.size() <= 1) {
        return list;
    }

    LinkedList left = new LinkedList();
    LinkedList right = new LinkedList();

    int middle = list.size() / 2;
    for(int i = 0; i < middle; i++) {
        left.add(list.get(i));
    }

    for(int i = list.size(); i >= middle; i--) {
        right.add(list.get(i));
    }

    left = sort(left);
    right = sort(right);

    return merge(left, right);
}

public LinkedList merge(LinkedList left, LinkedList right) {
    LinkedList result = new LinkedList();

    while(left.size() > 0 || right.size() > 0) {
        if(left.size() > 0 && right.size() > 0) {
            if(comparator.compare(left.get(0), right.get(0)) <= 0) {
                result.add(left.delete(0));
            }
            else {
                result.add(right.delete(0));
            }
        }
        else if(left.size() > 0) {
            result.add(left.delete(0));
        }
        else if(right.size() > 0) {
            result.add(right.delete(0));
        }
    }
    return result;
}   

}

在它中是“StackOverflowError Exception”。我试图删除bug,但我不能。谢谢你的帮助。

P.S对不起我的可怕语言。 :(

1 个答案:

答案 0 :(得分:0)

在第33行,您的上层数组索引需要从列表大小减去1开始:

        for(int i = list.size()-1; i >= middle; i--) {