bisect python 好用的的数组二分算法
bisect
是python自带的标准库。
其中bisect_left
是插入到左边,bisect_right
和bisect
是插入到右边
>>> a = [0, 1, 2, 3, 4]
>>> x = 2
>>> index = bisect.bisect(a,x)
>>> index
3
>>> a.insert(index,x)
>>> a
[0, 1, 2, 2, 3, 4]
def bisect_right(a, x, lo=0, hi=None, *, key=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
返回x项插入到列表a的下标,假设a是有序的
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(i, x) will
insert just after the rightmost x already there.
返回的值i使所有的在a[:i]范围中的e有e<= x,并且所有的在a[i:]范围中的e有e > x。所以如果x已经
在列表中,a.insert(i, x)将会插入到已经有的x的最右边
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
可选参数 lo 默认0和hi默认为len(a) 使寻找的切片边界
"""
if lo < 0:
raise ValueError('lo must be non-negative')#lo 必须是非负
if hi is None:
hi = len(a)
# Note, the comparison uses "<" to match the
# __lt__() logic in list.sort() and in heapq.
if key is None:
while lo < hi:
mid = (lo + hi) // 2
if x < a[mid]:
hi = mid
else:
lo = mid + 1
else:
while lo < hi:
mid = (lo + hi) // 2
if x < key(a[mid]):
hi = mid
else:
lo = mid + 1
return lo