搜索与排序

搜索指查询某个项是否在给定容器内,一般返回True or False

顺序搜索:

例1:无序表的顺序搜索

def search(alist,item):
    pos = 0
    found = False

    while pos < len(alist) and not found:
        if alist[pos] == item:
            found = True

        else:
            pos += 1

    return found

testlist = [8,7,15,3,10]
print(search(testlist,15))

例2:有序表的顺序搜索

def search(alist,item):
    found = False
    stop = False
    pos = 0

    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
    return found 

testlist = [4,8,10,15,23]
print(search(testlist,15))

二分法查找有序表:

def search(alist,item):
    found = False
    head = 0
    tail = len(alist)-1

    while head <= tail and not found:
        middle = (head + tail) // 2
        if item == alist[middle]:
            found = True
        elif item < alist[middle]:
            tail = middle - 1
        else:
            head = middle + 1
    return found

testlist = [4,6,8,10,15,17,22,29,31,36,40]
print(search(testlist,6))

 散列:(Hashing)

时间复杂度为O(1)

散列表(hash table) 槽(slot)  散列函数(hash  function)作用是将数据项映射到不同的槽中

渐变 --> 突变
原文地址:https://www.cnblogs.com/lybpy/p/8018319.html