最近在学爬虫的同时,也在恶补算法,参考图书为《算法图解》(Aditya Bhargava著)
先放上实现二分查找代码:
def binary_search(list,item):
low = 0
high = len(list)-1
count = 0 #查找计数
while high >= low:
count = count + 1
mid = int((low+high)/2)#后续选取公差为2的数列,方便mid取整
guess = list[mid]
if guess == item:
high = -1 #结束while循环
return count
elif guess > item:
high = mid - 1
elif guess < item:
low = mid + 1
构建函数,用于生成公差为2的,首项为1的等差数列
def test(N):
a = []
for i in range(N):
a.append(1+i*2)
return a
设item为1,实现最坏查找
引入matplotlib库,直观看出最坏情况下查找次数与总数的关系
import matplotlib.pyplot as plt
list = []
for i in range(2,10000):
list.append(binary_search(test(i),1))
plt.plot(list)
plt.show()
受限电脑性能,只能跑10000次循环~~,不过大致能看出二者关系为F(x)=log2n