二分查找(折半查找)

博客地址:https://www.cnblogs.com/zylyehuo/

时间复杂度:O(logn)

# _*_coding:utf-8_*_

def binary_search(li, val):
    left = 0
    right = len(li) - 1
    while left <= right:  # 候选区有值
        mid = (left + right) // 2
        if li[mid] == val:
            return mid
        elif li[mid] > val:  # 带查找的值在mid左侧
            right = mid - 1
        else:  # li[mid] < val 带查找的值在mid右侧
            left = mid + 1
    else:
        return None


li = list(range(1000))
print(binary_search(li, 389))

posted @ 2023-08-11 17:47  zylyehuo  阅读(7)  评论(0编辑  收藏  举报