Premise that this is homework, and I don't know why I can't use the tag 'homework', so I'll write it down here for clarity.
I have to write a method "int maximum(int[] a, int l, int r)" that finds the maximum in the array A spanning from 'l' to 'r' using a Divide and Conquer approach. Base Case will be when A has a single element inside, so if A.length == 1, return the element. The recursive part should divide the array in two subarrays spanning from A[l] to A[mid], and from A[mid+1] to A[r]. In theory I'm ok with that, but I keep getting a StackOverflowError and I don't understand why.
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;
}
}