递归与非递归实现二分查找法

匿名 (未验证) 提交于 2019-12-02 23:06:17

使用条件: 二分查找法适合用于不经常变动而查找频繁的有序列表。

1. 递归查找:

def binary_search(alist, item): 	"""二分查找法:递归查找""" 	n = len(alist) 	if n > 0: 		mid = n // 2 		if alist[mid] == item: 			return True 		elif item < alist[mid]: 			return binary_search(alist[:mid], item) 		else: 			return binary_search(alist[mid+1:], item) 	return False 

2. 非递归查找:

first = 0 last = len(alist) - 1 mid = (first + last) // 2 while first <= last: 	if alist[mid] == item: 		return True 	elif item < alist[mid]: 		last = mid - 1 	else: 	first = mid + 1 return False 
文章来源: https://blog.csdn.net/weixin_40576010/article/details/88591212
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!