Python实现查找算法

Posted 薛定谔的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python实现查找算法相关的知识,希望对你有一定的参考价值。

一.顺序查找---O(n)

无序列表查找

def sequentialSearch(alist,item):
	pos = 0
	found = False

	while pos < len(alist) and not found:
		if alist[pos] == item:
			found = True
		else:
			pos = pos + 1
	return found
list = [2,3,1,4,5,6,0]
print(sequentialSearch(list,5))
print(sequentialSearch(list,7))  

 

有序列表查找

def ordersequentialSearch(alist,item):
	pos = 0
	found = False
	stop = False
	while pos < len(alist) and not found and not stop:
		if alist[pos] == item:
			found = True
		else:
			if alist[pos] > item:
				stop = True
			else:
				pos = pos + 1
	return found
list = [1,2,3,4,5,6,7]
print(ordersequentialSearch(list,3))
print(ordersequentialSearch(list,9))

  

二.二分查找---O(log^n)

def binarySearch(alist,item):
	first = 0 
	last = len(list) - 1
	found = False

	while first <= last and not found:
		midpoint = (first + last) // 2
		if alist[midpoint] == item:
			found = True
		else:
			if item < alist[midpoint]:
				last = midpoint - 1
			else:
				first = midpoint + 1
	return found 
list = [0,1,2,3,4,5,6,7,8]
print(binarySearch(list,3))
print(binarySearch(list,10))  

 

递归实现二分查找

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

  

 

def sequentialSearch(alist,item):pos = 0found = False
while pos < len(alist) and not found:if alist[pos] == item:found = Trueelse:pos = pos + 1return foundlist = [2,3,1,4,5,6,0]print(sequentialSearch(list,5))print(sequentialSearch(list,7))


以上是关于Python实现查找算法的主要内容,如果未能解决你的问题,请参考以下文章

六大查找算法(Python 语言实现)

Python实现查找算法

二叉查找树简单实现

python数据结构与算法第十四天二分查找

Python实现经典查找算法

常用查找算法Python实现