码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现查找算法

时间:2018-01-30 19:30:00      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:列表   顺序   算法   not   实现   body   top   col   pac   

一.顺序查找---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实现查找算法

标签:列表   顺序   算法   not   实现   body   top   col   pac   

原文地址:https://www.cnblogs.com/wangxiayun/p/8386257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!