python实现二分查找算法

python实现二分查找法

def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high) // 2		# // 去尾整除,返回int
        guess = list[mid]

        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1

    return None


mylist = [1, 3, 5, 7, 9]
print(binary_search(mylist, 3))
print(binary_search(mylist, -1))

注意:

  1. 二分查找法必须顺序排列的列表才可以用
  2. 二分查找法的时间复杂度为O(logn)

关于对数log介绍

对数运算是幂运算的逆运算(log(2)可简写成log)
如:10^2 = 100 => log(10)100 = 2
10^3 = 1000 => log(10)1000 = 3

你可能感兴趣的:(算法)