运行此代码时出现堆栈溢出错误。我无法弄清楚背后的原因。 错误是在代码中生成的:mergeSort(input,beginIndex,midIndex); 合并排序(输入,midIndex + 1,endIndex的);
public class MergeSort {
public static void merge(int[] input, int beginIndex,int midIndex, int endIndex ) {
int[] temp = new int[25];
int k=beginIndex;
int left_end = midIndex-1;
int num_elements = endIndex-beginIndex+1;
while(beginIndex<=left_end && midIndex<=endIndex) {
if(input[beginIndex]<input[midIndex]) {
temp[k++] = input[beginIndex++];
}
else {
temp[k++] = input[midIndex++];
}
}
while(beginIndex<=left_end) {
temp[k++] = input[beginIndex++];
}
while(midIndex<=endIndex) {
temp[k++] = input[midIndex++];
}
for(int i=0;i<num_elements;i++) {
input[endIndex] = temp[endIndex];
endIndex--;
}
}
public static void mergeSort(int[] input, int beginIndex, int endIndex) {
if(beginIndex>=endIndex) {
return;
}
int midIndex = input.length/2;
mergeSort(input,beginIndex,midIndex);
mergeSort(input,midIndex+1,endIndex);
merge(input,beginIndex,midIndex,endIndex);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = {44,33};
mergeSort(array,0,array.length-1);
System.out.println("Sorted array is : ");
for(int i=0;i<array.length;i++) {
System.out.println(array[i]);
}
}
}
答案 0 :(得分:1)
由于midIndex的计算不正确,您创建了永远结束的循环:
public static void mergeSort(int [] input,int beginIndex,int endIndex){
int midIndex = input.length/2;
mergeSort(input,beginIndex,midIndex);//This is where issue is
代码中需要进行更正,如下所示:
int midIndex = (endIndex+beginIndex)/2;