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)
Math.floororMath.ceilthe value(low + high) / 2before assigning it tom. And you should use the same variables eitherlowandhighorlandh, not both.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.Math.floorkeeps the number in 64bit float.