二分法

295 阅读1分钟

二分法:二分法又称为折半查找,其输入是一个有序的元素列表(必须有序的原因稍后解释)。如果要 查找的元素包含在列表中,二分查找返回其位置;否则返回null。

适用范围:仅当列表是有序的时候,二分查找才管用。

示例代码

// JavaScript 版本
function binarySearch(arr, item) {
    /**
    定义每次开始和结束位置
    */
    let low = 0;
    let high = arr.length - 1;
    while (low <= high) { // 判断当两个元素相等时返回结果
        let mid = Math.round((high + low) / 2);
        let guess = arr[mid]; //获取中间元素
        if (guess === item) {
            return mid; // 返回索引
        } else if (guess > item) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return "None";
}
//python版本
def binary_search(list, item): 
  low = 0 
  high = len(list)—1 
  while low <= high: 
    mid = (low + high) 
    guess = list[mid] 
    if guess == item: 
      return mid 
    if guess > item: 
      high = mid - 1 
    else: 
      low = mid + 1 
  return None

时间复杂度:O(log n)以2为底

注意: 1.算法的速度指的并非时间,而是操作数的增速。
      2.谈论算法的速度时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加。
      3.算法的运行时间用大O表示法表示。
      4.O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快得越多。

注意

  1. 二分查找的速度比简单查找快得多。
  2. O(log n)比O(n)快。需要搜索的元素越多,前者比后者就快得越多。
  3. 算法运行时间并不以秒为单位。
  4. 算法运行时间是从其增速的角度度量的。
  5. 算法运行时间用大O表示法表示。