列表二分查询 & 遍历查询 & 递归二分
1、二分查找复杂度:O(logn)
2、遍历查询复杂度:O(n)
def common_search(lst,n):
"""遍历超找"""
for item in lst:
if item==n:
return n
return '未找到'
def bin_search(lst, n):
"""二分法查找,根据中间数改变索引即可"""
low_index = 0
high_index = len(lst)-1
while low_index<=high_index:
mid = (low_index + high_index) // 2
if lst[mid] > n:
high_index=mid-1
elif n == lst[mid]:
return mid
else:
low_index=mid+1
return '没到找'
def bin_search_recur(lst,n,low,high):
"""方法同上,采用递归"""
mid = (low+high)//2
if low<=high:
if lst[mid]>n:
return bin_search_recur(lst,n,low,mid-1)
elif n == lst[mid]:
return mid
else:
return bin_search_recur(lst, n, mid+1, high)
return None
import time
start_time = time.time()
lst = list(range(10000000))
# bin_search(lst,9999900)
# common_search(lst,9999900)
bin_search_recur(lst,9999900,0,9999999)
end_time = time.time()
print('耗时:%s' % (end_time-start_time))
# 二分查询耗时:0.21814703941345215
# 遍历查找耗时:0.9246125221252441
# 二分递归耗时:0.23915982246398926