function binarySearch(array, value) {
let low = 0,
high = array.length - 1;
while (low <= high) {
let mid = (low + high) / 2;
if (value === array[mid]) {
return mid;
} else if (value < array[mid]) {
high = mid - 1;
} else if (value > array[mid]) {
low = mid + 1;
}
}
console.log('值不存在');
return undefined;
}
重写
查找前需要排序
function binarySearch(arr,value){
if(arr.length === 0) return null
let bottom = 0,
top = arr.length - 1
while(bottom<=top){
let index = Math.floor((bottom+top)/2)
if(arr[index] === value){
return index
}else if(arr[index]>value){
top = index - 1
}else if(arr[index]<value){
bottom = index + 1
}
}
return null
}