使用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
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 基于websocket和swoole的简易聊天室
- 下一篇: unity3d打包发布Apk流程
