早上好,您不必总是使用列表的中间位置进行搜索(二进制搜索),而是可以根据最大值(最后一项),最小值(第一项)和搜索值。 ((假定项目的均匀分布,并且对项目进行了排序。))这是我的下面代码,您会提出任何建议吗?
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]打印(binary_search(a,6))
好吧,如果您可以对数据进行假设,那么是的,这样的优化是可能的。实际上,如果您假设数据始终是唯一的数字1..100
,没有任何空格,则可以使它甚至faster