排序和搜索(一)——python實現順序查找

【基本原理】當數據存儲在諸如列表的集合中時,我們就說它具有線性或順序關係。在python列表中,數據項存儲的位置是單個索
引值,並且索引值是有序的,順序查找就可以按照索引順序逐個比較,直到找到或者遍歷整個列表
【無序列表查找分析】圖片來自:problem-solving-with-algorithms-and-data-structure-using-python

【代碼】
#假定是無序排列
def sequentialSearchUnorder(alist,item):
    found=False
    post=0
    while not found and post<len(alist):
        if alist[post]==item:
            found=True
            print(item,'在',post+1,'位上')
        else:
            post=post+1
    return found
print(sequentialSearchUnorder([1,52,6,3,9,11,488,56,54,2,4,6,7,89],6))
【有序列表順序查找】如果列表按照值升序排列,在數據1,3,5,7,9,12,45,89,91,95,96中,找40,發現到45時還沒有找到,
那我們就可以停止遍歷,因爲45及其後面的數都是大於40的,故可以停止查找

【有序列表查找分析】

圖片來自:problem-solving-with-algorithms-and-data-structure-using-python


【代碼】
#假定項是有序(升序),輸入的列表是有序的
def sequentialSearchOrder(alist,item):
    found=False
    post=0
    stop=False
    while not found and post<len(alist) and not stop:
        if alist[post]==item:
            found=True
            print(item,'在',post+1,'位上')
        elif alist[post]>item:
            stop=True
            print('不存在')
        else:
            post=post+1
    return found

print(sequentialSearchOrder([1,3,5,7,9,12,45,89,91,95,96],9))

結果展示

6 在 3 位上True9 在 5 位上True

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章