我的Binary Search算法有问题。我正在尝试用javascript实现它,但仍然会遇到无限循环。这是我的代码:
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)
var a = [1, 4, 5, 8, 11, 15]
function binarySearch(arr, item){
let low = 0
let 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;
} else {
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)