Smit
Smit

Reputation: 35

Binary search always return -`

I am trying to implement binary search using JS but it's going into an infinite loop. It's not returning the position. I am not sure what's the mistake I am doing.

Code:

function binarySearch(value, list) {
    let initial = 0;
    let end = list.length - 1;
    let found = false;
    let middle;
    let position = -1;
  
    while (found != true && initial <= end){
      middle = Math.round(initial + end) / 2;
      if (value == list[middle]) {
      found = true;
      position = middle;
      } else if (value < list[middle]) end = middle - 1;
      else initial = middle + 1;
  }
      console.log(position) ;
  
  }
binarySearch(3, [1, 3, 5, 6]);

Upvotes: 2

Views: 109

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 710

The following code is always true, hence an infinite loop.

while (found != true && initial <= end)
    middle = Math.round(initial + end) / 2;

Put the code inside the curly bracket


function binarySearch(value, list) {
  let initial = 0;
  let end = list.length - 1;
  let found = false;
  let middle;
  let position = -1;

  while (found != true && initial <= end){
    middle = Math.round((initial + end) / 2);
    if (value == list[middle]) {
    found = true;
    position = middle;
    } else if (value < list[middle]) end = middle - 1;
    else initial = middle + 1;
}
    return position;i

}

Upvotes: 0

TyGuy96
TyGuy96

Reputation: 172

You have middle = Math.round(initial + end) / 2; which not always results in an integer.

Change it to middle = Math.round((initial + end) / 2); to always get an integer.

Upvotes: 1

Related Questions