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

143
Visualizações
Why my while loop doesn't break and keeps logging the searched index in my binary search with infinite times?

Using javascript, I have been trying binary search and I have taken a while loop which will loop the list of numbers till the first index is less than equal to the last. Then I calculate the midpoint or mean and compare the midpoint index value with the input value. When it matches, it shows the index of the input value but the loop never ends.

function binary_search(value, array){
  var first = 0;
  var last = array.length - 1;

  while(first <= last){
    var midpoint = Math.floor((first + last) / 2);

    if(array[midpoint] == value){
      console.log(midpoint);
    }else if(array[midpoint] < value){
      first = midpoint + 1;
    }else if(array[midpoint] > value){
      last = midpoint -1;
    }
    
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There isnt anything to stop your loop, once it hits your if statement

if(array[midpoint] == value){
     console.log(midpoint);
}

And that if statement returns true as your neither returning, breaking or changing the values of first/last anymore the loop will just keep looping. You should most likely include a break statement within that if statement. Like:

function binary_search(value, array){
  var first = 0;
  var last = array.length - 1;

  while(first <= last){
    var midpoint = Math.floor((first + last) / 2);

    if(array[midpoint] == value){
      console.log(midpoint);
      break;
    }else if(array[midpoint] < value){
      first = midpoint + 1;
    }else if(array[midpoint] > value){
      last = midpoint -1;
    }
    
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
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