Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda