基于这是一道作业题,我不知道为什么不能使用“作业”标签,所以我在此清晰地写下。
我需要编写一个方法 "int maximum(int [] a, int l, int r)" ,使用分治法查找从'l'到'r'的数组A中的最大值。 基本情况是当A中只有一个元素时,如果A.length == 1,则返回该元素。 递归部分应将数组分成两个子数组,从A [l]到A [mid],从A [mid + 1]到A [r]。 理论上我没问题,但我一直得到 StackOverflowError 错误,我不明白为什么。
我需要编写一个方法 "int maximum(int [] a, int l, int r)" ,使用分治法查找从'l'到'r'的数组A中的最大值。 基本情况是当A中只有一个元素时,如果A.length == 1,则返回该元素。 递归部分应将数组分成两个子数组,从A [l]到A [mid],从A [mid + 1]到A [r]。 理论上我没问题,但我一直得到 StackOverflowError 错误,我不明白为什么。
public class Maximum {
public static void main(String[] args) {
int[] A = {0, 5, 281, 3, 9, 4, 88, 16, 17, 60};
int l = 0;
int r = A.length-1;
System.out.println("Maximum of the array: "+maxArray(A, l, r));
}
public static int maxArray(int[] A, int l, int r) {
//Assuming that the index of array is '0' and not '1', l is 0. Else, put 1.
if (A.length == 1) {
return A[l];
}
int mid = r/2;
int maxLeft = 0;
int maxRight = 0;
maxLeft = maxArray(A, l, mid); //Here is the StackOverflowError!
maxRight = maxArray(A, mid+1, r);
if (maxLeft < maxRight) {
return maxRight;
} else
return maxLeft;
}
}