1

I have a problem with my Binary Search algorithm. I'm trying to implement it in javascript but still it get a infinity loop. Here's my code:

var a = [1, 4, 5, 8, 11, 15]

function binarySearch(arr, item){
  let low = 0
  let high = arr.length - 1

  while(low <= high) {
    var m = (low + high)/2 | 0
    if(arr[m] == item){
        console.log("Item found in index: " + m)
      return false;
    } else {
            if(a[m] > item){
            console.log("Too high")
          h = m - 1
        } else {
            console.log("Too low")
          l = m + 1
        }
    }
  }
  console.log("Item not found")
  return false;
}

binarySearch(a, 1)
4
  • You should Math.floor or Math.ceil the value (low + high) / 2 before assigning it to m. And you should use the same variables either low and high or l and h, not both. Commented Dec 11, 2017 at 15:09
  • 3
    while(low <= high) You don't actually modify either of those variables inside the loop so if the condition starts as true it can never become false. Commented Dec 11, 2017 at 15:09
  • 1
    Ok, thanks i didn't noticed that i use "l" and "h" instead of "low" and "high". Now it's working, thanks a lot. Btw. Math.floor is working the same as | 0 Commented Dec 11, 2017 at 15:14
  • @sh3ev, no, bitwise OR converts a number to first to 32 bit and then back to 64 bit float, whereas Math.floor keeps the number in 64bit float. Commented Dec 11, 2017 at 15:43

1 Answer 1

2

Try this (editted something wrong from your code):

var a = [1, 4, 5, 8, 11, 15]

function binarySearch(arr, item) {
    var low = 0
    var high = arr.length - 1

    while (low <= high) {
        let m = low + (high - low ) / 2
        if (arr[m] == item) {
            console.log("Item found in index: " + m)
            return false;
        }
        if(a[m] > item) {
            console.log("Too high")
            hight = m - 1
        } else {
            console.log("Too low")
            low = m + 1
        }
    }
    console.log("Item not found")
    return false;
}

binarySearch(a, 1)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.