Fork me on GitHub

随笔 - 997  文章 - 5  评论 - 181  阅读 - 300万 

  顺序查找算法是一种很基本的查找算法,该算法的复杂度一般是最大是O(n),假如加上顺序查找,算法的复杂度

还要降一倍,为O(n/2)。

  Python的代码实现如下所示:

  

复制代码
def sequential_search(a_list,item):
        pos = 0
        found = False

        while pos < len(a_list) and not found:
                if a_list[pos] == item:
                        found = True
                else:
                        pos = pos + 1

        print("pos:%d"%pos)

        return found

def ordered_sequential_search(a_list,item):
        pos = 0
        found = False
        stop = False

        while pos < len(a_list) and not found and not stop:
                if a_list[pos] == item:
                        found = True
                else:
                        if a_list[pos] > item:
                                stop = True
                        else:
                                pos = pos + 1
        print("pos:%d" % pos)
        return found

test_list = [1,2,8,13,17,19,32,43,0]
test_lista = [15,18,2,19,18,0,8,14,19,14]
test_listb = [3,5,6,8,11,12,14,15,17,18]
print(sequential_search(test_lista,18))
print(sequential_search(test_lista,13))
print(ordered_sequential_search(test_list,3))
print(ordered_sequential_search(test_listb,13))
复制代码

  运算结果:

  

pos:1
True
pos:10
False
pos:2
False
pos:6
False

 

posted on   虚生  阅读(592)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示