简单的二分搜索
Blog
破事水
const source = [10, 3, 35, 24, 10, 9, 23, 14, 15, 56]
const target = 23
source.sort((a, b) => a - b)
console.log(`source: ${source}`)
console.log(`target: ${target}`)
/**
* 破二分搜索
* @param {Array[int]} array 源数组
* @param {int} low 搜索下界
* @param {int} high 搜索上界
* @param {int} target 搜索目标
*/
function BinarySearch (array, low, high, target) {
if (low > high) {
return false
}
let mid = Math.floor((high + low) / 2)
if (array[mid] > target) {
return BinarySearch(array, low, mid - 1, target)
} else if (array[mid] < target) {
return BinarySearch(array, mid + 1, high, target)
} else {
return mid
}
}
console.log(`result: ${BinarySearch(source, 0, source.length, target) + 1}`)
简单的二分搜索
Blog
破事水