Python 二分查找

Python 中自带了bisect模块实现了二分查找

def merge_search(list, num):
    list.sort()
    start, end = 0, len(list)-1  # 数组下标
    while start < end:
        mid = (start + end) // 2
        if list[mid] < num:
            start = mid + 1      # 更新数组下标
        elif list[mid] > num:
            end = mid - 1        # 更新数组下标
        else:
            return mid
    return -1


temp = [1, 2, 0, 5, 7]
num = [5, 4]
for i in num:
    print(merge_search(temp, i))
    from bisect import bisect_left, bisect_right, bisect
    print(bisect_left(temp, i))    # 在列表中查询目标值num, num存在时返回X左侧的位置, 不存在则返回X应该插入的位置, 返回值为index
    print(bisect_right(temp, i))   # 在列表中查询目标值num, num存在时返回X右侧的位置, 不存在则返回X应该插入的位置, 返回值为index
    print(bisect(temp, i))    # <=> bisect_right

3
3
4
4
-1
3
3
3

  

原文地址:https://www.cnblogs.com/frank-shen/p/10289957.html