import random
defLinear_search(li,val):for index,v inenumerate(li):if v == val:return index
li =list(range(10))
val =3
random.shuffle(li)# 打乱顺序print(li)
Linear_search(li,val)# [4, 3, 7, 2, 8, 6, 1, 9, 5, 0]# 1
二分查找
时间复杂度 O(logn)
必须先排好序
defBinear_search(li,val):
left =0
right =len(li)-1while left <= right:
mid =(right+left)//2if li[mid]== val:return mid
elif li[mid]> val:
right = mid -1else:
left = mid +1
li =list(range(10))
val =3
random.shuffle(li)print(li)
Linear_search(li,val)# [2, 6, 5, 3, 7, 0, 4, 9, 8, 1]# 3
比较线性查找和二分查找效率
# 封装一个计算时间的函数import time
defcal_time(func):defwarpper(*args,**kwargs):
t1 = time.time()
result = func(*args,**kwargs)
t2 = time.time()print("%s running time: %s secs."%(func.__name__, t2-t1))return result
return warpper
@cal_time#修饰函数defLinear_search(li,val):for index,v inenumerate(li):if v == val:return index
@cal_timedefBinear_search(li,val):
left =0
right =len(li)-1while left <= right:
mid =(right+left)//2if li[mid]== val:return mid
elif li[mid]> val:
right = mid -1else:
left = mid +1
li =list(range(100000))
val =3600
random.shuffle(li)
Linear_search(li,val)
Binear_search(li,val)# Linear_search running time: 0.12470626831054688 secs.# Binear_search running time: 0.0 secs.
顺序查找时间复杂度 O(n)import randomdef Linear_search(li,val): for index,v in enumerate(li): if v == val: return index li = list(range(10))val = 3random.shuffle(li) # 打乱顺序print(li)Linear_search(li,val)# [4, 3, 7, 2, 8,