我在Java中使用MergeSort實現時遇到問題。我的代碼看起來像這樣,我不知道我犯了什麼錯誤。MergeSort算法 - java
public List sort(List list) {
return mergesort(list, 0, list.size() - 1);
}
private List mergesort(List list, int startIndex, int endIndex) {
if (startIndex == endIndex) {
List temp = new ArrayList();
temp.add(list.get(0));
return temp;
}
int splitIndex = ((startIndex + endIndex)/2);
List list1 = mergesort(list, startIndex, splitIndex);
List list2 = mergesort(list, (splitIndex + 1), endIndex);
return merge(list1, list2);
}
private List merge(List left, List right) {
List result = new ArrayList();
ListIterator l = new ListIterator(left);
ListIterator r = new ListIterator(right);
l.first();
r.first();
while (!l.isDone() && !r.isDone()) {
if (comparator.compare(l.current(), r.current()) <= 0) {
result.add(l.current());
l.next();
} else {
result.add(r.current());
r.next();
}
}
while (!l.isDone()) {
result.add(l.current());
l.next();
}
while (!r.isDone()) {
result.add(r.current());
r.next();
}
return result;
}
爲了測試我的算法我用的人名單和排序他們按年齡上升:
0. Jan, Kowalski, 60
1. Jerzy, Adamczewski, 59
2. Jan, Kowalski, 48
3. Adam, Malysz, 40
4. Bartosz, Tusk, 50
5. Zygmunt, Jacewicz, 41
和輸出是這樣的:
0. Adam, Malysz, 40
1. Adam, Malysz, 40
2. Adam, Malysz, 40
3. Adam, Malysz, 40
4. Adam, Malysz, 40
5. Adam, Malysz, 40