zoukankan      html  css  js  c++  java
  • 有序查找和二分查找

    有序查找:

    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
  • 相关阅读:
    WebView.简单使用_ZC代码
    WebView.简单使用_资料
    APK.错误解决_Theme.AppCompat.Light相关
    USB调试.红米Note4X
    Android_连接数据库_资料收集
    APK签名_ZC
    APK签名_资料
    ubuntu系统中代替windows系统中onenote软件--basket note pads
    firefox浏览器设置新页面后激活
    oracle 写declare例子
  • 原文地址:https://www.cnblogs.com/yqpy/p/8696320.html
Copyright © 2011-2022 走看看