二分查找
内置模块bisect.bisect实现二分查找, bisect.insort二分插入
def bisect_right(iterable, search_value, lo=0, hi=None): """Return the index where to insert item search_value in list iterable, assuming iterable is sorted. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(iterable) while lo < hi: mid = (lo+hi)//2 if search_value < iterable[mid]: hi = mid else: lo = mid+1 return lo
自己写一个二分查找:
def bin_search(li, val): low = 0 high = len(li) - 1 while low <= high: mid = (low + high) // 2 if li[mid] == val: return mid elif li[mid] > val: high = mid - 1 else: low = mid + 1 return None