二分查找

今天写一个二分查找的实例,里面会涉及到random模块的使用

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))

二分查找有个前提,就是列表必须是有序的!

人生苦短,何不用python
原文地址:https://www.cnblogs.com/yqpy/p/8953407.html