Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Attempting to find the sum of an array using divide and conquer using JavaScript but is outputting undefined

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!