二分查找基于索引,所以必须是有序的
def binary_search(list, item):
high = len(list) - 1
low = 0
# 如果不加=号,无法计算两端的数字(1,7)
while low <= high:
mid = (high + low) // 2
guess = list[mid]
if guess == item:
return mid
elif guess < item:
low = mid + 1
else:
high = mid - 1
return None
ret = binary_search([1, 3, 5, 7], 5)
print(ret) # 1
网友评论