对于学校,我正在尝试编写一个递归排序算法。但是由于某种原因,它并没有停止在基本情况下,将不胜感激。错误是
java.lang.StackOverflowError
这是方法:
public static List recursiveMergeSort(List<Integer> list1){
List<Integer> list = list1;
List<Integer> listR = new ArrayList<>();
List<Integer> listL = new ArrayList<>();
int counter =0;
if(list.size() == 1){
return list;
} else {
for (int i = 0; i <list.size()/2-1; i++){
listL.add(list.get(i));
}
for(int i = list.size()/2; i < list.size()-1; i++) {
listR.add(list.get(i));
}
recursiveMergeSort(listL);
recursiveMergeSort(listR);
list = merge(listL, listR);
counter++;
}
return (list);
}
public static List merge(List<Integer> listL, List<Integer> listR){
int leftIndex = 0;
int rightIndex = 0;
int listIndex = 0;
List<Integer> list = new ArrayList<>();
while(leftIndex < listL.size() && rightIndex < listR.size()){
if(listL.get(leftIndex) <= listR.get(leftIndex)){
listR.add(listIndex, listL.get(leftIndex));
leftIndex = leftIndex + 1;
}else {
list.add(list.get(listIndex), listR.get(rightIndex));
rightIndex = rightIndex +1;
}
listIndex = listIndex + 1;
}
if(leftIndex < listL.size()){
copyRest(listL, leftIndex, list, listIndex);
} else {
copyRest(listR, rightIndex, list, listIndex);
}
return (list);
}
感谢您的帮助!
答案 0 :(得分:1)
问题出在两个内部的for循环中:
for (int i = 0; i <list.size()/2-1; i++){ // should be i<list.size()/2
listL.add(list.get(i));
}
for(int i = list.size()/2; i < list.size()-1; i++) { //should be i < list.size()
listR.add(list.get(i));
}
最初,当您提供大小为5的输入时,listR获得两个元素(具有索引2和3的元素),并且在对listR的递归调用中,不会执行任何for循环,因此递归调用将一直进行直到你得到一个错误