python - 修改二分查找功能
问题描述
早上好,你可以根据最大值(最后一项)、最小值(第一项)和搜索值来估计要搜索的项的位置,而不是总是使用列表的中间进行搜索(二分查找) .
((假设项目的均匀分布和排序的项目。))这是我下面的代码,你们有任何建议的代码吗?
def binary_search(seq,item):
"""It uses non recursive method to search the item in the given seq.
It returns the position of item if found, None otherwise"""
left_index=0
right_index=len(seq)-1
while left_index <= right_index: #stop searching when left_index > right_indext
mid_index=(right_index + left_index)//2 #find the mid point
if seq[mid_index]==item:
return mid_index
elif seq[mid_index]>item:
right_index = mid_index -1 #if mid point ele > search ele, move right pointer
else:
left_index = mid_index + 1 #if mid point ele < search ele, move left pointer
return None
a=[1,2,3,4,5,6,7,8,9]
print(binary_search(a,6))
解决方案
假设物品的均匀分布并且物品被排序。
撇开二进制搜索需要排序数据而不管您在哪里选择分割点这一事实不谈,对数据做出假设的能力意味着像这样的优化是可能的。
事实上,如果您假设数据始终是1..100
没有间隙的唯一数字,您可以让它更快:-)
当然,这对于一般情况并没有真正的帮助,如果你在数据集上运行你的算法,你会看到它{ 1, 2, 3, 4, 5, ..., 100, 99999999 }
,寻找100
.
您的算法希望在数组的早期而不是倒数第二个索引中找到它。
假设数据集属性的能力已在许多情况下成功使用。例如,在哈希查找中使用英文姓氏,您可以给出以他们自己的存储桶开头的名称,同时E
将那些以 、 和 开头的Z
名称集中到一个存储桶中(假设以 开头的名称比其他名称更常见) .X
V
Y
E
推荐阅读
- php - 如何在 PHP 中获取以“@”和数字开头的最后一个字符串?
- javascript - 为什么不显示存储的对象?
- php - WooCommerce:在自定义循环中添加产品选项卡
- json - 从python中的http响应中删除k,v
- node.js - Discord.js 异步和等待
- python - 如何退出第二个循环以增加我的第一个循环以创建两个二维数组?
- python - 如何防止 QGraphicsItem 相互碰撞
- c++ - 我真的不明白将二维数组传递给函数
- python - Python-Binance 模块 futures_historical_klines start_str 不工作
- td-engine - 如何设置TDengine缓存某个表的最后一行?