import math
def binary_search(list0, item):#list是已知的数组,item是要在list中寻找的数
low = 0
high = len(list0) - 1
while low <= high:
mid = math.floor((low + high) / 2)#Python2中有自动向下取整功能,python3中没有,所以要导入math模块中的向下取整方法math.floor
guess = list0[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]
print(binary_search(my_list, 7))
print(binary_search(my_list, 2))
最终运行结果:
3
None