def binary_search(list, item):
# low和high用于跟踪要在期中查找的列表部分
low = 0
high = len(list) - 1
# 只要范围没有缩小到只包含一个元素
while low <= high:
# 就检查中间的元素
mid = (low + high) // 2
guess = list[mid]
# 找到了元素
if guess == item:
return mid
# 猜的数字大了
if guess > item:
high = mid - 1
# 猜的数字小了
else:
low = mid + 1
# 没有指定的元素
return None
my_list = [1, 3, 5, 7, 9]
# 别忘了索引从0开始,第二个位置的索引为1
print(binary_search(my_list, 3)) # => 1
# 在Python中,None表示空,它意味着没有找到指定的元素
print(binary_search(my_list, -1)) # => None
1.二分查找
最新推荐文章于 2020-10-21 23:39:35 发布