Python 遞迴實現二分查詢
阿新 • • 發佈:2018-12-18
def binarychop(lst, target, head, tail): if isinstance(lst, list): if len(lst) == 0: return -1 head = head tail = tail target = target middle = (head + tail) // 2 if lst[middle] == target: return 1 elif lst[middle] > target: if tail == 0 or tail < head: return -1 else: tail -= 1 return binarychop(lst, target, head, tail) else: if head == len(lst) - 1 or head > tail: return -1 else: head += 1 return binarychop(lst, target, head, tail) else: return -1