我的mergesort()实现遇到了问题,因为im返回一个数组我在mergesotrt()中遇到stackoverflow错误。我的merge()工作正常这是一个小剪贴画我的整个程序有一个ArraytoString()工作正常并打印到控制台我添加在alsp我不允许更改实现类型,如基本格式必须保持 {37,27,43,3,9,81,10}
public static int[] merge(int[] arr1, int start, int mid, int end, int[] temp) {
int beginHalf1 = start;
int endHalf1 = mid;
int beginHalf2 = mid+1;
int endHalf2 = end;
//if odd its mid half of
int index = 0;
//until arraysect runs out check which is smaller and send to temp
while (beginHalf1 <= endHalf1 && beginHalf2 <= endHalf2){
if(arr1[beginHalf1] <= arr1[beginHalf2]){
temp[index] = arr1[beginHalf1];
beginHalf1++;
}else {//>=
temp[index] = arr1[beginHalf2];
beginHalf2++;
}
index++;
}//pass leftover items to array
if(beginHalf1>endHalf1){//right half not done
while (beginHalf2<=endHalf2){
temp[index] = arr1[beginHalf2];
beginHalf2++;
index++;
}
}else if(beginHalf2>endHalf2){ //left half not done
while (beginHalf1<=endHalf1){
temp[index] = arr1[beginHalf1];
beginHalf1++;
index++;
}
}
return temp;
}
public static int[] mergeSort(int[] arr, int start, int end, int[] temp) {
//arr unsorted returns sorted copy of that array
//idk why it doesnt run
if (start < end) {
int mid = ((start + end) / 2)-1;//offset for mid for odd size
mergeSort(arr, start, mid, temp);
mergeSort(arr, mid + 1, end, temp);
merge(temp, start, mid, end, temp);
}
return temp;//what do i return
}
public static void main(String[] args) {
int[] arr = {37, 27, 43, 3, 9, 81, 10};//3,9,10,27,39,43
int length = sortedmerge.length/2-1;//-1 offset for mid
arrayToString(mergeSort(arr,0,arr.length,new int[arr.length]));
}
答案 0 :(得分:0)
if (start < end) {
int mid = ((start + end) / 2) - 1; //offset for mid for odd size
mergeSort(arr, start, mid, temp);
mergeSort(arr, mid + 1, end, temp);
merge(temp, start, mid, end, temp);
}
start
永远不会小于mid
所以你mergeSort(arr, start, mid, temp);
的第一次调用似乎进入了导致stackoverflow的infine循环。