小白学python--二分查找法

二分查找:通过对待查找的值与有序列表的中间值进行比较,输出查找结果。

时间复杂度为:Olog(n)

#二分法查找学号,并打印出这一个学号学生的信息
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,20)
        id=ids[i]          
name=random.choice(a1)+random.choice(a2)+random.choice(a3) result.append({"id":id,"age":age,"name":name}) return result def Binary_search(List,val):#查找符合要求的学号 low=0 high=len(List)-1 while low<=high: mid=(low+high)//2 if List[mid]['id']==val: print(List[mid]) return mid elif List[mid]["id"]<val: low=mid+1 else: high=mid-1 print("里面没有")#只有在查不到的情况下才会执行这条指令 List=random_list(100) val_dict=1070 Binary_search(List,val_dict)

 

posted @ 2018-04-15 15:15  鱼萌哒  阅读(153)  评论(0)    收藏  举报