二分查找(binary-search)是一种算法,输入是一个有序的元素列表(仅当列表是有序的时候,二分查找才管用)。若查找的元素包含在列表中,二分查找返回其位置,否则返回null。
1.查找的范围
low = 0
high = len(list) -1
2.检查中间的元素
mid = (low + high)/2 # 如果(low + high)是奇数,python自动将mid向下圆整
guess =list[mid]
#猜的数字小了,修改low
if guess < item:
low = mid +1
#猜的数字大了,修改high
if guess > item:
high = mid -1
3. 完整代码如下:
def binary_search(list,item):
low = 0
high = len(list)-1
while low <= high:
mid = int((low + high)/2)
guess = list[mid]
if guess == item:
return mid
elif guess > item:
high = mid -1
else:
low = mid +1
return None
my_list= [1,3,5,7,9]
print(binary_search(my_list,3))
print(binary_search(my_list, -1))
D:\python\routin\python.exe E:/pychar/ab.py
1
None
来源:CSDN
作者:认真且怂(//)
链接:https://blog.csdn.net/qq_35623978/article/details/104277042