Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda