使用python实现二分查找

来源:互联网 发布:360解压软件下载 编辑:程序博客网 时间:2024/06/04 23:22
import mathdef 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 Nonemy_list = [1, 3, 5, 7, 9]print(binary_search(my_list, 7))print(binary_search(my_list, 2))            

最终运行结果:

3None


原创粉丝点击