參考:
1. 順序查找 | 博客園
?
基本思想:
?
順序查找,就是從第一個元素開始,按索引順序遍歷待查找序列,直到找出給定目標或者查找失敗。
特點:
1. 對待查序列(表)無要求 --?待查找序列可以是有序,也可以是無序;
2. 從第一個元素開始;
3. 需要逐一遍歷整個待查序列(除非已經找到);
4. 若查找到最后一個元素還沒找到,則查找失敗;
?
缺點:
效率低 --?需要遍歷整個待查序列
?
時間復雜度:
O(n),平均查找時間 = 列表長度/2
空間復雜度:
1個待查序列+1個目標元素 <=> O(n)
?
看一組示例,從一組數據[3,6,7,2,12,9,0,11]中查找12,
初始狀態:指針p指向列表第一個元素,即索引為0元素,開始向右滑動,以匹配、查找目標
?
Step1:p指針開始向右滑行一個單位,進行比較
Step2,3,直到4:查找到元素12,匹配目標12成功,索引=4
?
示例代碼
data = [3,6,7,2,12,9,0,11]""" sequence search """ def seqsearch(array, target):i = 0for i in range(len(array)):element = array[i]if element == target:print 'sucess to find out %d from array, index=%d'%(target, i)return iprint 'fail to find out the target'return -1print seqsearch(data, 12) #sucess to find out print seqsearch(data, 8) #fail to find out
運行結果
sucess to find out 12 from array, index=4 4 fail to find out the target -1
?