使用python实现二分查找
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
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
