二分查找


定义

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。

运行时间

O(log n)

输入

有序列表,列表项

输出

对应列表项的下标

代码

// JavaScript版本
function binarySearch(list, item) {
  let low = 0
  let high = list.length - 1
  while (low <= high) {
    console.log('Search once');
    let mid = parseInt((low + high) / 2)
    let guess = list[mid]
    if (guess === item) {
      return mid
    }
    if (guess > item) {
      high = mid - 1
    } else {
      low = mid + 1
    }
  }
  return null
}

myList = [1, 3, 5, 7, 9]
console.log(binarySearch(myList, 5)) // => 2
# Python 版本
def binary_search(list, item):
  low = 0
  high = len(list) - 1
  while low <= high:
    print('Search once')
    mid = (low + high) // 2
    guess = list[mid]
    if guess == item:
      return mid
    if guess > item:
      high = mid -1
    else:
      low = mid + 1
  return None

my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3)) # => 1
print(binary_search(my_list, -1)) # => None
原文地址:https://www.cnblogs.com/huangtq/p/15423834.html