顺序查找法:
顺序查找,字如其名:按照顺序挨个查找,该查找的算法复杂度为O(n)
def sequentialSearch(alist,item):
found = False
for i in range(len(alist)):
if alist[i] == item:
found = True
print("这个数在第{}位置为{}".format(i,alist[i]))
print (found)
testlist = [1,4,5,6,3,9,2,7]
sequentialSearch(testlist,7)
二分法查找:
二分查找的算法复杂度为O(log n),但是需要列表按顺序排列,所以对于一次排序多次查找比较实用
def binarySearch(alist,item):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
if alist[(last + first) // 2] == item:
found = True
print("在第{}个位置找到{}".format((last + first) // 2,item))
elif alist[(last+first) // 2] < item:
first = (last+first) // 2 + 1
else:
last = (last+first) // 2 - 1
return found
testlist = [1,2,3,4,5,6,7,8,9]
print(binarySearch(testlist,66))
二分法查找实际上体现了解决问题的典型策略:分而治之
将问题分为若干小规模,通过小规模部分解决问题并将结果汇总得到原来问题的解。
显然,递归算法是一种典型的分而治之策略的算法,所以二分法也适合用递归算法来实现:
def binarySearch(alist,item):
olist = alist
if len(olist) == 0:
return False
elif olist[len(olist) // 2] == item:
return True
elif olist[len(olist) // 2] < item:
return binarySearch(olist[len(olist) // 2 +1:],item)
else:
return binarySearch(olist[:(len(olist) // 2)],item)
testlist = [1,2,3,4,5,6,7,8,9]
print(binarySearch(testlist,6))
我们在此处用到了列表切片,而切片操作的复杂度是O(k),这样会使得整个算法时间复杂度稍有增加,而且切片改变了列表,同样也不容易找到查找元素在列表中的位置。