Javascript 无限循环二元搜索算法
我的二进制搜索算法有问题。我试图用javascript实现它,但它仍然得到一个无限循环。这是我的密码:Javascript 无限循环二元搜索算法,javascript,algorithm,search,binary-search,Javascript,Algorithm,Search,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){ co
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]
函数二进制搜索(arr,项){
设低=0
let high=arr.length-1
while(低项){
console.log(“太高”)
h=m-1
}否则{
console.log(“过低”)
l=m+1
}
}
}
console.log(“未找到项”)
返回false;
}
二进制搜索(a,1)
试试这个(编辑了代码中的错误):
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;
}
var a=[1,4,5,8,11,15]
函数二进制搜索(arr,项){
var低=0
var高=阵列长度-1
while(低项){
console.log(“太高”)
高度=m-1
}否则{
console.log(“过低”)
低=m+1
}
}
console.log(“未找到项”)
返回false;
}
二进制搜索(a,1)在将值分配给
m
之前,您应该Math.floor
或Math.ceil
值(低+高)/2
。您应该使用相同的变量,或者是low
和high
或者l
和h
,而不是两者都使用。while(low Ok,谢谢,我没有注意到我使用了“l”和“h”而不是“low”和“high”.现在它工作了,非常感谢。顺便说一句,数学。地板和|一样工作0@sh3ev、否、按位或将数字先转换为32位,然后再转换回64位浮点,而Math.floor
将数字保持为64位浮点。