function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
while (left <= right) {
const midIndex = Math.floor((left + right) / 2)
if (target === arr[midIndex]) {
return midIndex
} else if (target < arr[midIndex]) {
right = midIndex - 1
} else {
left = midIndex + 1
}
}
return -1
}
const arr = [1, 3, 5, 7, 8]
console.log(binarySearch(arr, 5)) // 2
console.log(binarySearch(arr, 4)) // -1
javascript-实现二分查找
最新推荐文章于 2024-10-02 05:39:15 发布