二分查找是一种算法,其输入是一个有序的元素列表。
如果要查找的元素包含在列表中,二分查找返回其位置;否则返回null
一般而言,对于包含n个元素的列表,用二分查找最多需要log2n步,而简单查找最多需要n步
def binary_search(bucket:list, item:int)->int:
low = 0
high = len(bucket)-1
while low<=high:
mid = (low+high)//2
guess = bucket[mid]
if guess == item:
return mid
if guess > item:
high = mid -1
else:
low = mid+1
bucket = list(range(1,20))
binary_search(bucket,21)
'''
'该数字不在数组中'
'''
binary_search(bucket,12)
'''
11
'''