Given a sequence of integers, how can I find the average of it using a divide and conquer approach? I have to write a method "double avg(int[] a, int l, int r)" that finds the average in the array A, spanning from 'l' to 'r' as homework, but I get a StackOverflowError on the first recursive call - not in the second, though! - of my code, and I can't seem to understand why. Also, I'm pretty sure it doesn't give me a true average, but I found no way to check the average of a sequence using the divide and conquer. Here is my code:
public class Average {
public static void main(String[] args) {
int[] A = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int l = 0;
int r = A.length-1;
System.out.println("Average of the array: "+averageCheck(A, l, r));
}
public static double averageCheck(int[] A, int l, int r) {
if (l==r) {
return A[l];
}
// Base Case: if there's just a single element it is the average of the array itself
int mid = (l+r)/2;
double avLeft = 0;
double avRight = 0;
avLeft = A[l]/r + averageCheck(A, l, mid);
avRight = A[mid+1]/r + averageCheck(A, mid+2, r);
double average = ( (avLeft*mid) + (avRight * (r-mid) ) ) /r;
return average;
}
}
StackOverflowError) The average of a sequence of integers is the sum divided by the length. Don't do the division until the end. Particularly don't divide byr, that is meaningless. - Andy Turner