欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法图解 1.2 二分查找

程序员文章站 2022-05-05 18:00:19
...

1.2 二分查找

仅当列表是有序时,二分查找才管用
例子:
binary_search
书中代码大致如下:

# 二分查找
def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        """只要范围没有缩小到只含有一个元素,就检查中间的元素"""
        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

但是,会报错!!
TypeError: list indices must be integers or slices, not float

将其中:mid = (low + high) / 2
改为:mid = int((low + high) / 2)
即可顺利运行