重学数据结构与算法——二分查找

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:
            right = mid - 1
        elif Li[mid] < val:
            left = mid + 1
    else:
        return None
test = [1,2,3,4,5,6]
print(test)
print(binary_search(test, 3))

你可能感兴趣的:(重学数据结构与算法)