码迷,mamicode.com
首页 > 编程语言 > 详细

python 数据结构--查找

时间:2018-03-25 14:25:51      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:span   sea   pad   lin   log   ima   技术分享   https   inline   

1 顺序查找O(n)

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
    return found
test_list = [1, 2, 32, 8]
print sequential_search(test_list, 3)
print sequential_search(test_list, 32)

2 二分查找O(lgn)

def binary_search(a_list, item):
    first = 0
    last = len(a_list)-1
    found = False
    while first <= last and not found:
        midpoint = (first+last)//2
        if a_list[midpoint] == item:
            found = True
        elif a_list[midpoint] < item:
                first = midpoint+1
        else:
            last = midpoint-1
    return found
test_list = [1, 2, 3, 4, 5, 6]
print binary_search(test_list, 3)
print binary_search(test_list, 0)

3 哈希查找O(1)

概念:来自wikipedia

技术分享图片

python 数据结构--查找

标签:span   sea   pad   lin   log   ima   技术分享   https   inline   

原文地址:https://www.cnblogs.com/huangqiancun/p/8643877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!