Skip to main content

前端基础算法——二分查找

· One min read
Harry
Front End Engineer

前端基础算法——二分查找

二分查找,其查找的列表必须有序。时间复杂度为:O(log n)

二分查询/简单查询对比(查找数23)

二分查询/简单查询对比(查找数1)

function binarySearch (list, item) {
// 保存最小与最大位置
let min = 0
let max = list.length - 1

// 最小位置是否小与等于最大位置
while (min <= max) {
let index = Math.floor((min + max) / 2)
let val = list[index]

if (val === item) {
return index
} else if (val > item) {
max = index - 1
} else {
min = index + 1
}
}
return null
}

binarySearch