Python 数据结构--查找

Posted on 2018-03-25 12:40  _hqc  阅读(156)  评论(0编辑  收藏  举报

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

hash