算法图解——01.二分查找

                                     算法图解——01.二分查找

 时间复杂度:O(logn)

每次都检查中间元素

# 二分查找: 仅当列表为有序的时候,二分查找才管用

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = int((low + high) / 2)  # list indices must be integers or slices, not float 进行强制类型转换
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:  # 猜大了 注意:索引是从0开始的
            high = mid - 1
        else:  # 猜小了
            low = mid + 1
    return None


my_list = [1, 2, 3, 5, 8, 9, 11, 22, 80, 90, 100]
test1 = binary_search(my_list, 8)
test2 = binary_search(my_list, 100)
print(test1)  # 4
print(test2)  # 10

猜你喜欢

转载自blog.csdn.net/qq_43299522/article/details/108863307