0
我一直有我的mergesort()实现的问题,因为我返回一个数组,我得到mergesotrt()中的stackoverflow错误。我的merge()工作正常这是一个小的clippet我的整个程序有一个ArraytoString()哪些工作正常,并打印到控制台即时通讯添加在alp im不允许更改实现类型,如基本格式必须保持 {37,27 ,43,3,9,81,10}JAVA mergeSort返回数组
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]));
}