二分查找

好久不见. 提交于 2019-12-01 12:17:56

 

 

# 二分查找
def binary_search(li, val):
    low=0
    high=len(li)
    while low <= high:
        mid = (low+high) // 2
        if li[mid] == val:
            return mid
        elif li[mid] < val:
            low = mid +1
        else:
            high =mid - 1
    return None


l=[1,2,3,4,5,6,7,8,9]
li = list(range(0,10000))
d = binary_search(l,4)
print(d)

 

# 递归版本的二分
def bin_search_rec(data_set, value, low, high):
    if low<=high:
        mid = (low + high) //2
        if data_set[mid]== value:
            return mid
        elif data_set[mid] > value:
            return bin_search_rec(data_set, value, low,mid - 1)
        else:
            return bin_search_rec(data_set, value, mid +1,high)
    else:
        return 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!