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

141
Views
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 answers
Answer question

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 Report
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!