最近在学习python,由于在面试中,二分查找算法面试率极高,所以使用python做了一个实现。
def search1(sequence, number): lower = 0 upper = len(sequence) - 1 while lower <= upper: mid = (lower + upper) // 2 if number > sequence[mid]: lower = mid + 1 elif number < sequence[mid]: upper = mid - 1 else: return mid return -1
def search(sequence, number, lower, upper): if lower == upper: assert number == sequence[upper] return upper else: middle = (lower + upper) // 2 if number > sequence[middle]: return search(sequence, number, middle + 1, upper) else: return search(sequence, number, lower, middle)
时间: 2024-12-17 18:51:11