排序和搜索(一)——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

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