二分查找

 

 

# 二分查找
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 

 

posted @ 2019-10-16 13:52  虫洞小鳗鱼  阅读(124)  评论(0编辑  收藏  举报