I understand that finding the sum of numbers in an array is much more easily done through iteration instead of recursion, but if I were to use recursion to write such a function, what would be wrong with this code?
public static double sum (double[] a) {
if (a.length == 0)
return 0.0;
else{
return sumHelper (a, 1, a[0]);
}
}
private static double sumHelper (double[] a, int i, double result) {
if (i < a.length) {
result = result + sumHelper (a, i + 1, result);
}
return result;
}
Everything runs without errors, yet does not return the correct sum when I test it out.
sumHelper
to return the sum on a range. If the range has length 1, return that element's value. Otherwise split the range in half, recursively callsumHelper
on each half, and return the sum the results. This isn't any less work, but will give O(log n) growth to the stack and allow you to deal with much larger arrays.