深度比较二分查找与bisect_right函数


插在右边的核心观点就是right所在元素的位置必须是 a[mid] > x 因此if a[mid]>x : right=mid
插在左边的核心观点就是right所在的位置是a[mid]>= x,因此 a[mid]>=x :right=mid

而无论是插在右边还是左边,left = mid+1,因为mid这个答案显然不是正确的,我们必须把他排除出去,以提高效率

现在还有一个问题,就是为什么我们的终结迭代条件是left<right,而不是类似二分查找那样left<=right
从前面的描述我们可以看到,a[right]这个位置的数字始终是>a或者是>=a,因此当left=right时,我们是已经满足退出条件了,就不用再进行迭代,并且right的初始值是len(a),而不是len(a)-1
另外有一个令right=len(a)的原因是,我们插入数据的位置可能是len(a),


那么我们还是有一个疑问,为什么二分查找的情况下,right的初始值是right=len(a)-1,而不是len(a),这是因为我们
假定x是在a中的,此时我们返回的值肯定是属于a中元素的索引,而不会其他位置的索引
那为什么在二分查找中,在left=right的情况下我们还是需要进行迭代啊,这是因为我们真的需要判断a[mid]==x,只有其真的相等我们才要返回
而在bisect_right中,我们一定可以找到一个位置插入我们虚妄插入的数据

def bisect_right(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        # Use __lt__ to match the logic in list.sort() and in heapq
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo


def bisect_left(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e < x, and all e in
    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
    insert just before the leftmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        # Use __lt__ to match the logic in list.sort() and in heapq
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值