So I am attempting to get my head around the divide and conquer principle and multiple recursive calls in a single method. It's going ok but I have a problem with the output of the method I am writing.
The purpose of the method is to return the sum of all the pairs of consecutive numbers in an array. I am 95% there but am not getting the output I expect and have been banging me head against the desk for ages trying to work out why.
The array is:
int[] array = { 11, 6, 87, 32, 15, 5, 9, 21 };
and the method is:
public int consecutivePairsSum_DivideAndConquer(int start, int end, int[] array) {
int leftSum;
int rightSum;
int middle = (start + end) / 2;
if (start == middle) {
return array[middle];
} else {
leftSum = array[start] + array[start + 1];
leftSum += consecutivePairsSum_DivideAndConquer(start, middle, array);
}
if (middle == end) {
return array[end];
} else {
rightSum = array[middle] + array[middle+1];
rightSum += consecutivePairsSum_DivideAndConquer(middle+1, end, array);
}
return leftSum + rightSum;
}
Here's my method call:
System.out.println(rF.consecutivePairsSum_DivideAndConquer(0, array.length-1, array));
I think it must be something to do with how I have split the array but no amount of experimenting is giving me the right output.
Expected output: 340
Actual output: 330
Any suggestions most welcome, this is driving me nuts! :p
ps Any useful links to where I can find a solid online tutorial/good book about recursion would also be great (if that's within the scope of SO seeing how it's not direct help with a programming issue)