Saani Info
Saani Info

Reputation: 73

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;
    }
    
  }
}

Upvotes: 1

Views: 49

Answers (1)

DevWithZachary
DevWithZachary

Reputation: 3675

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;
    }
    
  }
}

Upvotes: 1

Related Questions