查找算法之顺序查找
查找算法中最直观最容易理解的就是顺序查找了,思路比较简单,就是在顺序表(包括链表)中按次序逐个比较,直到找到或者遍历完线性表。关键点是顺序遍历。
def sequentialSearch(alist, item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos += 1
if found:
return pos
else:
return found
testlist = [1,2,32,8,17,19,42,13,0]
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
这是一般情况下的顺序遍历,如果能找到的情况下,最坏是比较n次,最好是比较1次,找不到的情况下,就是n次,时间复杂度就是O(n)。其实如果顺序表示有序的话,其实可以进一步优化。即当如果 当前元素比要查找的元素大时,那么就没必要继续向下查找了,因为后面的一定比当前元素大,一定不存在了。
def sequentialSearch(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 += 1
if found:
return pos
else:
return found
testlist = [0,1,2,8,13,17,19,32,42]
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
那么这样的话,能找到的情况下时间复杂度还是那样,找不到的情况下(即不存在要查找的元素),最好的就是比较1次,即第一个元素就比要查找的元素大,所以后面的元素一定比要查找的元素大,肯定不存在要查找的元素。