[英]Where am i going wrong with my recursive binary search?
def BinarySearch(aList, first, last, target):
assert 0 <= first < len(aList); last < len(aList)
if len(aList) == 0:
return False
pos = first + last / 2
pos = round(pos)
if aList[pos] == target:
return pos
else:
if target <= aList[pos]:
return BinarySearch(aList[:pos], first, pos, target)
else:
return BinarySearch(aList[pos +1 :], pos + 1, last, target)
This is a school problem and the arguments are input through another function. 这是一个学校问题,参数是通过另一个函数输入的。 The test function passes an array with 6 values and my code finds the first 3 but not the last ones. 测试函数传递具有6个值的数组,而我的代码找到前3个,但没有找到最后一个。
you could do: 你可以做:
def BinarySearch( aList, first, last, target ):
if first < 0 or last < 0 or first > last or first >= len(aList):
return -1
if len( aList ) == 0:
return -1
pos = (first + last) // 2
if aList[pos] == target:
return pos
elif aList[pos] > target:
return BinarySearch( aList, first, pos - 1, target )
else:
return BinarySearch( aList, pos + 1, last, target )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.