二分查找——基于python

最近在学爬虫的同时,也在恶补算法,参考图书为《算法图解》(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
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值