我写了下面的代码,但我得到了堆栈溢出。单独测试时,合并方法可以正常工作。当我现在查看代码时,我有隧道视野,我无法理解为什么它不起作用,所以有人可以向我指出错误。非常感谢!
public static List<Comparable> mergeSort(List <Comparable> target){
if(target.size() < 2)
return target;
return merge(mergeSort(copy(0,(target.size()-1)/2 + 1,target)),mergeSort(copy((target.size()-1)/2 + 1,target.size(),target)));
}
private static List<Comparable> merge(List<Comparable> target1,List<Comparable> target2){
List <Comparable> result = new ArrayList <Comparable>();
while(target1.size() > 0 || target2.size() > 0){
if(target1.isEmpty())
result.add(target2.remove(0));
else if(target2.isEmpty())
result.add(target1.remove(0));
else if(target1.get(0).compareTo(target2.get(0)) < 0)
result.add(target1.remove(0));
else
result.add(target2.remove(0));
}
return result;
}
private static List<Comparable> copy(int startIndex, int endIndex, List<Comparable> target){
List <Comparable> result = new ArrayList <Comparable>();
for(int i = startIndex; i < endIndex; i++)
result.add(target.get(i));
return result;
}