【发布时间】:2015-06-16 18:33:51
【问题描述】:
此代码的输出始终是输入的最后一位。 找不到原因。我递归使用归并排序,结果是错误的。我想可能是列表重叠了。
public class MergeSort {
public static List<Integer> Sort(List<Integer> list) {
if (list.size() <= 1) {
return list;
}
List<Integer> aList = new ArrayList<Integer>();
aList = list.subList(0, list.size() / 2);
List<Integer> bList = new ArrayList<Integer>();
bList = list.subList(list.size() / 2, list.size());
Sort(aList);
Sort(bList);
merge(aList, bList, list);
return list;
}
private static List<Integer> merge(List<Integer> alist,
List<Integer> blist, List<Integer> list) {
int alistIndex = 0, blistIndex = 0, listIndex = 0;
while (alistIndex < alist.size() && blistIndex < blist.size()) {
if (alist.get(alistIndex) < blist.get(blistIndex)) {
list.set(listIndex, alist.get(alistIndex));
alistIndex++;
} else {
list.set(listIndex, blist.get(blistIndex));
blistIndex++;
}
listIndex++;
}
List<Integer> rest;
if (alistIndex == alist.size()) {
rest = blist.subList(blistIndex, blist.size());
for(int c = blistIndex; c < rest.size(); c++){
list.set(listIndex, blist.get(c));
listIndex++;
}
} else {
rest = alist.subList(alistIndex, alist.size());
for(int c = alistIndex; c < rest.size(); c++){
list.set(listIndex, alist.get(c));
listIndex++;
}
}
return list;
}
}
测试输入为 5、4、3、2、1。 但是输出是 1, 1, 1, 1, 1。 所以,这个合并方法肯定有问题
【问题讨论】:
-
您是否使用调试器单步调试过您的代码?
-
您应该使用调试器,并可能在每一步打印排序列表的内容以检查输出。