Traditionally, I know in most cases divide and conquer algorithms divide the parent array into two subarrays in order to perform the desired operation and then merge it all back together. In my case, I am attempting to divide the parent array into three subarrays rather than two and merging it all back together in order to determine the sum of all integers in the array. However, during testing, it outputs as undefined. I assume this is due to mid1 and mid2 somehow not being properly defined or something is wrong with my recursion.
My Code (Compiled with Node.js):
function divideAndConquerSum(a) {
return divideAndConquerSumMerge(a, 0, a.length - 1);
}
function divideAndConquerSumMerge(a, low, high) {
if (high == low) return a[low];
var mid1 = low + (high - low) / 3;
var mid2 = mid1 + (high - low) / 3;
return (
divideAndConquerSum(a, low, mid1 - 1) +
divideAndConquerSum(a, mid1 + 1, mid2 - 1) +
divideAndConquerSum(a, mid2 + 1, high)
);
}
let a = [1, 5, -1, 4];
console.log(divideAndConquerSum(a));
The expected output should be 9, but it returns undefined instead. Edit: No longer has overloaded functions. Now gives a stack overflow error.