顺序查找法:
顺序查找,字如其名:按照顺序挨个查找,该查找的算法复杂度为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<