1. 程式人生 > >Python 遞迴實現二分查詢

Python 遞迴實現二分查詢

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