搜索

搜索是在一个 item 集合中找到一个特定 item 的算法过程。搜索通常返回的答案是 True 或 False,即该 item 是否存在。搜索的几种常见方法:顺序查找、二分法查找、二叉树查找、哈希查找。本篇博客主要介绍二分法查找。

二分法查找

二分查找又称为折半查找,优点是比较次数少,查找速度快,平均性能好;缺点是要求待查找的表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

首先,假设表中元素是按升序排序,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分为前、后两个子表,如果中间位置的记录的关键字大于查找关键字,则下一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满意条件的记录,此时查找成功,或直到子表不存在为止,此时查找不成功。

查找python中tuple python查找功能_数据结构

二分法查找 Python 实现

非递归实现

def binary_search(alist, item):
	first = 0
	last = len(alist) - 1
	while first <= last:
		mid = (first + last) // 2
		if alist[mid] == item: 
			return True
		elif item < alist[mid]: 
			last = mid - 1
		else: 
			first = mid + 1
	return False

可采用如下测试

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))

递归实现

def binary_search(alist, item):
	if len(alist) == 0: return False
	else:
		mid = len(alist) // 2
		if alist[mid] == item:
			return True
		else:
			if item < alist[mid]: 
				return binary_search(alist[:mid], item)
			else:
				return binary_search(alist[mid + 1:], item)

时间复杂度

  • 最优时间复杂度:查找python中tuple python查找功能_二分法_02
  • 最坏时间复杂度:查找python中tuple python查找功能_数据结构_03