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))
Output: "5"
如何改进上面的代码?
我想item
根据max value
(最后一项)、min value
(第一项)和search value
. 我上面的代码正在使用中间的list
搜索,这将需要更长的时间才能到达。
谁能告诉我在哪里可以更改我的代码并进一步改进它?
解决方案
推荐阅读
- vba - 分配给一个对象导致另一个对象也发生变化
- vue.js - 无法读取本地主机上未定义的属性“获取”
- perl - Perl 哈希在访问它的未定义值时被错误地初始化
- javascript - 如何CSS网格最后大小
- python - 如何按不同的值对一个 Pandas 数据框列的元素进行切片?
- single-sign-on - 得到“弹性没有正确加载。检查服务器输出以获取更多信息。” 通过网守访问时
- java - 将汽车绘制为多边形并使其在 Java Swing 中移动
- xaml - 如何更改工具栏颜色?(xamarin.forms)
- windows - 在 windows cmd 中为 conf 文件指定环境变量
- spring-boot - SpringBoot Config Server 文件分隔符问题