• 有序查找和二分查找


    有序查找:

    def linear_search(data_set,value):
        for i in range(len(data_set)):
            if data_set[i] == value:
                return i
        return

    二分查找:

    def bin_search(data_set,value):
        low=0
        high = len(data_set)-1
        while low <= high:
            mid = (low+high)//2
            if data_set[mid] == value:
                return mid
            elif data_set[mid] > value:
                high = mid-1
            else:
                low = mid+1
    
    
    a = bin_search(range(1,40),24)
    print(a)

    注意:要求列表一定是有序的

    例子:给定一个学生名单,包括姓名,年龄,id,按id从小到大有序排列,要求给出任意id值,查找对应的学生信息

    import random
    
    def random_list(n):
        result = []
        ids= list(range(1001,1001+n))
        a1 = ['','','','']
        a2 = ['','']
        a3 = ['','']
        for i in range(n):
            age = random.randint(18,60)
            id = ids[i]
            name = random.choice(a1)+random.choice(a2)+random.choice(a3)
            dict = {
                'id':id,
                'name':name,
                'age':age,
            }
            result.append(dict)
        return result
    
    def bin_search(data_set,value):
        low=0
        high = len(data_set)-1
        while low <= high:
            mid = (low+high)//2
            if data_set[mid]['id'] == value:
                return data_set[mid]
            elif data_set[mid]['id'] > value:
                high = mid-1
            else:
                low = mid+1
    
    data_set = random_list(10000)
    print(bin_search(data_set,7654))

    两种算法的时间复杂度分别为O(n)和O(logn)

    人生苦短,何不用python
  • 相关阅读:
    vue-router2.0 组件之间传参及获取动态参数
    vuex
    移动端微信部分知识总结
    移动端js知识总结
    [luogu]P4365[九省联考]秘密袭击coat(非官方正解)
    [luogu]P4364 [九省联考2018]IIIDX
    [luogu]P4363 [九省联考2018]一双木棋chess
    后缀数组自用
    BZOJ5288 [Hnoi2018]游戏
    Bzoj5290: [Hnoi2018]道路
  • 原文地址:https://www.cnblogs.com/yqpy/p/8696320.html
Copyright © 2020-2023  润新知