How to write binary code looks without error

There are several binary search wording? What is the difference between them? - Jason Li answer - know almost
https://www.zhihu.com/question/36132386/answer/530313852

The median: two larger of the median. The median is the next smaller one.

The realization of binary search to find the decomposed upper bound and a lower bound to find two functions

def lower_bound(array, first, last, value): # 返回[first, last)内第一个不小于value的值的位置
    while first < last: # 搜索区间[first, last)不为空
        mid = first + (last - first) // 2  # 防溢出
        if array[mid] < value: first = mid + 1
        else: last = mid
    return first  # last也行,因为[first, last)为空的时候它们重合

def upper_bound(array, first, last, value): # 返回[first, last)内第一个大于value的位置
    while first < last:
        mid = first + (last - first)//2
        if array[mid] <= value: first = mid + 1
        else: last = mid
    return first

Note conversion relationship:

Seeking the minimum position x> = value of: lower_bound (first, last, value)

Seeking x> value of the minimum position: upper_bound (first, last, value)

Find x <= value of the maximum position: upper_bound (first, last, value) - 1

Guess you like

Origin www.cnblogs.com/ZeroTensor/p/11111308.html
Recommended