查找算法之顺序查找Python

查找算法之顺序查找

查找算法中最直观最容易理解的就是顺序查找了,思路比较简单,就是在顺序表(包括链表)中按次序逐个比较,直到找到或者遍历完线性表。关键点是顺序遍历。

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次,即第一个元素就比要查找的元素大,所以后面的元素一定比要查找的元素大,肯定不存在要查找的元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值