python 写二分查找函数

代码如下:

#二分查找

def binary_search(list,item):
    low = 0  # 跟踪数组索引
    high = len(list)-1
    while low <= high: # 只要数组中有元素
        mid = (low + high) // 2 #每次循环改变中间的索引
        guess = list[mid] 
        if guess == item: # 找到目标元素
            return mid
        elif guess < item: #范围小了,排除了前面一半的元素
            low = mid + 1 #最前面的索引加1
        else: #如果guess > item,排除了后面一半的元素
            high = mid - 1  #接着最后的索引要在最中间的基础上-1,因为list[mid]已经被排除了
    return None # 如果在数组中找不到要查找的元素,返回None

猜你喜欢

转载自blog.csdn.net/weixin_42233629/article/details/80469385
今日推荐