Chapter 6: Sorting and Searching
# 知识解析
6.4 Binary Search
"""
condition should be a function that evaluates as
[False, False ... True, True, True], aka >= target
"""
def bsearch_low(arr: List[int], condition: Callable[[int], bool]) -> Optional[int]:
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
smaller = condition(arr[mid])
if smaller:
high = mid - 1
else:
low = mid + 1
if low >= len(arr) or not condition(arr[low]):
return None
return low
"""
condition should be a function that evaluates as
[True, True ... False, False, False], aka <= target
"""
def bsearch_high(arr: List[int], condition: Callable[[int], bool]) -> Optional[int]:
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
bigger = condition(arr[mid])
if bigger:
low = mid + 1
else:
high = mid - 1
if high < 0 or not condition(arr[high]):
return None
return highLast updated