算法-二分查找-python实现

本文介绍了一种使用数组实现的二分查找(binary_search)算法。该算法适用于已排序的数据集,并展示了其实现细节及时间复杂度分析。通过随机测试案例验证了算法的有效性和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
import random

'''
采用数组的方式实现binary_search
数组元素必须有序排列

时间复杂度为对数级别(2为底)
'''

def binary_search(list,item):
    if len(list):
        low=0
        high=len(list)-1

        while low <= high:
            mid=int((low+high)/2)
            guess=list[mid]

            if guess > item:
                high=mid-1
            if guess < item:
                low=mid+1
            if guess == item:
                return mid
    else:
        return None

# def binary_search(list,item):
#     low=0
#     high=len(list)-1

#     while low <= high:
#         mid=int((low+high)/2)
#         guess=list[mid]

#         if guess > item:
#             high=mid-1
#         if guess < item:
#             low=mid+1
#         if guess == item:
#             return mid 
#     return None

#测试代码

my_list=[x for x in range(0,100)]
find=0
notfind=0
for x in range(0,100):
    item=random.randint(0,100)
    mid=binary_search(my_list,item)
    if not mid:
        notfind=notfind+1
    else:
        find=find+1
        print("item:%d,index:%d" %(item,mid))

print("*************我是分割线**************")
print("Match %d times \t don't match %d times " %(find,notfind))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值