Javascript 为什么这个二进制搜索找不到我的值?
大家好,我的二进制搜索一直返回“未找到”,因为它找不到我传递给它的值。请让我知道我做错了什么,谢谢Javascript 为什么这个二进制搜索找不到我的值?,javascript,binary-search,Javascript,Binary Search,大家好,我的二进制搜索一直返回“未找到”,因为它找不到我传递给它的值。请让我知道我做错了什么,谢谢 const binary\u search=(arr,value)=>{ 让高=arr.length-1; 设low=0; 设mid=0; 而(低arr[中]){ //把低处往上移一点 低=中+1; }否则{ //把高的移到下一个 高=中-1; } } 返回“未找到” } 让数组=[12,45,37,37,84,61,12,266] 设sorted=array.sort(函数(a,b){返回a-b
const binary\u search=(arr,value)=>{
让高=arr.length-1;
设low=0;
设mid=0;
而(低arr[中]){
//把低处往上移一点
低=中+1;
}否则{
//把高的移到下一个
高=中-1;
}
}
返回“未找到”
}
让数组=[12,45,37,37,84,61,12,266]
设sorted=array.sort(函数(a,b){返回a-b})
设wif=二进制搜索(排序,37)
console.log(已排序)
console.log(wif)
您的代码显示:
mid = Math.floor = ((high + low) / 2)
我不认为这就是你的意思const binary\u search=(arr,value)=>{
const binary_search = (arr, value) => {
let high = arr.length -1;
let low = 0;
let mid = 0;
while (low <= high){
mid = Math.floor = ((high + low) / 2)
mid = Math.round(mid);
//middle value being searched
if (arr[mid] == value){
//return value
return arr[mid];
} else if (value > arr[mid]){
// move the low up one
low = mid + 1;
} else {
// move the high down one
high = mid -1;
}
}
return 'not found'
}
let array = [12, 45, 37, 37, 84, 61, 12, 266]
let sorted = array.sort (function(a,b){return a-b})
let wif = binary_search(sorted,37)
console.log(sorted)
console.log(wif)
让高=arr.length-1;
设low=0;
设mid=0;
而(低arr[中]){
//把低处往上移一点
低=中+1;
}否则{
//把高的移到下一个
高=中-1;
}
}
返回“未找到”
}
让数组=[12,45,37,37,84,61,12,266]
设sorted=array.sort(函数(a,b){返回a-b})
设wif=二进制搜索(排序,37)
console.log(已排序)
console.log(wif)
mid=Math.floor=((高+低)/2)的值在每次迭代中都是整数,因此无法获得索引。如7/2=3.5和arr[3.5]。没有价值。试试
mid=Math.floor((高+低)/2)
是的,这很有效,谢谢!
const binary_search = (arr, value) => {
let high = arr.length -1;
let low = 0;
let mid = 0;
while (low <= high){
mid = Math.floor = ((high + low) / 2)
mid = Math.round(mid);
//middle value being searched
if (arr[mid] == value){
//return value
return arr[mid];
} else if (value > arr[mid]){
// move the low up one
low = mid + 1;
} else {
// move the high down one
high = mid -1;
}
}
return 'not found'
}
let array = [12, 45, 37, 37, 84, 61, 12, 266]
let sorted = array.sort (function(a,b){return a-b})
let wif = binary_search(sorted,37)
console.log(sorted)
console.log(wif)