欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 递归实现二分查找

程序员文章站 2024-03-19 15:41:34
...
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