zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    Git 操作
    SVN
    一维数组
    常见的数学方法
    常用事件
    function函数
    while;do while; for循环
    JS中的变量提升
    关于js的单双引号嵌套问题
    db.collection is not a function
  • 原文地址:https://www.cnblogs.com/frank-shen/p/10289957.html
Copyright © 2011-2022 走看看