二分搜索(python实现)

def binary_search(list,item):
    low = 0
    high = len(list)-1
    while(low <= high):
        mid = (low + high)//2
        guess = list[mid]
        if(item == guess):
            return mid
        if(item > guess):
            low = mid + 1
        elif (item < guess):
            high = mid - 1
    return None

my_list = [1,3,5,7,9,34,56,89,789]

print(binary_search(my_list,56))#6
print(binary_search(my_list,-1))#None

猜你喜欢

转载自blog.csdn.net/weixin_45253216/article/details/110195078
今日推荐