二分查找(上)
Posted 编程加油站
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找(上)相关的知识,希望对你有一定的参考价值。
二、二分查找的时间复杂度
三、二分查找的递归与非递归实现
1、非递归实现
// 数组必须有序 不存在重复
const biaryFind = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target === sortedArr[mid]) {
return mid
} else if (target < sortedArr[mid]) {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
const arr = [1, 4, 5, 6, 7, 8, 10, 11, 23, 42, 44, 54, 56, 77, 102]
console.log(biaryFind(arr, 44))
2、递归实现
// 递归方式实现二分查找
const binaryFindRecursion = (sortedArr, target) => {
return bsearchInternally(sortedArr, 0, sortedArr.length - 1, target)
}
const bsearchInternally = (array, low, high, target) => {
if (low > high) return -1
let mid = low + ((high - low) >> 1)
if (array[mid] === target) {
return mid
} else if (array[mid] < target) {
return bsearchInternally(array, mid + 1, high, target)
} else {
return bsearchInternally(array, low, mid - 1, target)
}
}
const sortedArr = [1, 4, 5, 6, 7, 8, 10, 11, 23, 42, 44, 54, 56, 77, 102]
console.log(binaryFindRecursion(sortedArr, 23))
四、二分查找的局限性
以上是关于二分查找(上)的主要内容,如果未能解决你的问题,请参考以下文章