【发布时间】:2018-02-26 22:44:55
【问题描述】:
我必须使用偏移量进行二进制搜索,所以没有左或右变量。如果找不到该项目,我需要让它返回 None ,但无论出于何种原因,我都对如何做到这一点感到困惑。我知道你能做到
if right >= left:
#search function here
else: return None
但我没有这些变量,它不适用于 array[mid:] >= array[:mid]
这里是函数
def binary_search(array, item, offset=0):
mid = int(len(array)/2) #make mid an int so it truncates
if item == array[mid]: #if the item is at mid, we're done
return mid + offset
elif item > array[mid]: #if the item is bigger than the item at mid, go to right side of array
return binary_search(array[mid:], item, offset+mid) #add the mid value to offset since we're going right
else: #otherwise, the value is smaller and we go to the left side of the array
return binary_search(array[:mid], item, offset) #leave offset the same
我尝试了很多不同的东西,但我似乎无法弄清楚。谢谢!
【问题讨论】:
标签: python offset binary-search