请问我的这个程序问题在哪里?报错说“Exception in thread "main" java.lang.StackOverflowError”
package array;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] array = {4, 8, 2, -5, 7, 11, 2};
MergeSort(array, 0, array.length-1);
System.out.println(Arrays.toString(array));
}
public static void MergeSort(int[] array, int left, int right) {
if(left >= right) {
return;
}
int mid=(right - left) / 2;
MergeSort(array, left, mid);
MergeSort(array, mid+1, right);
merge(array, left, mid, right);
}
public static void merge(int[] array, int left, int mid, int right) {
int[] temp = new int [right - left + 1];
int leftIndex = left;
int rightIndex = mid + 1;
int t = 0;
while(leftIndex <= mid && rightIndex <= right) {//Compare left and right sub-array and store the small
if(array[leftIndex] <= array[rightIndex]) { //one in temp[].
temp[t] = array[leftIndex];
t++;
leftIndex++;
}else {
temp[t] = array[rightIndex];
t++;
rightIndex++;
}
}
while(leftIndex <= mid) {//If there are any element left in the left sub-array, copy to temp[]
temp[t] = array[leftIndex];
t++;
leftIndex++;
}
while(rightIndex <= right) {//If there are any element left in the right sub-array, copy to temp[]
temp[t] = array[rightIndex];
t++;
rightIndex++;
}
for(int t1 = 0; t1 < temp.length; t1++) {
array[t1 + left] = temp[t1];
}
}
}
递归没有终止 方法调用累加太多
MergeSort方法里面 int mid=(right - left) / 2; 改为 int mid=(right + left) / 2;