I wrote the below program to find the sum of all integers using divide and conquer recursion algorithm in Java:
But somehow the sum is coming incorrectly.
public class DivideAndConquerSum {
public static void main(String[] args) {
int[] arr = new int[]{2, 3, 4, 5};
System.out.println(calculateRecursiveSum(arr, 0, arr.length));
}
static long sum = 0;
static long calculateRecursiveSum(int[] arr, int low, int high) {
if (high == low) {
return arr[0];
} else {
int mid = (high + low) / 2;
sum = calculateRecursiveSum(arr, low, mid) +
calculateRecursiveSum(arr, mid + 1, high);
}
return sum;
}
}
Can anyone please let me know what is wrong in the code to resolve it? Assuming only positive integers in this scenario.
high
parameter is the index of the last item to be included in the sum, or the last +1. In this case, starting withhigh = arr.length
says it's last +1, but that's not consistent with thesum = ....
recursion, which misses outarr[mid]
. Ifhigh
was the last item to be included in the sum,return arr[0]
would need to bereturn arr[low]
, but everything else then works as is -- except you start witharr.length - 1
of course, and you need to watch out forarr.length == 0
. It's the old "out by 1" gotcha.