js实现二分法查找
2021-01-09 06:30
标签:code lse arch console sea pre bin 查找 ret js实现二分法查找 标签:code lse arch console sea pre bin 查找 ret 原文地址:https://www.cnblogs.com/bejamin/p/13526167.htmlconst arr1 = [1,4,5,8,12,16,18]
function binarySearch(arr, num) {
let len = arr.length
let leftIndex = 0
let rightIndex = len - 1
while(leftIndex arr[mid]) { // 比中间值大,说明在 mid 到 rightIndex 之间;否则就在 mid 到 leftIndex 之间
leftIndex = mid + 1
} else {
rightIndex = mid - 1
}
}
return -1 // 没找到返回-1
}
console.log(binarySearch(arr1, 12))