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

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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