要修复代码,需要返回else语句:
def binary_search_recursive(array: list[int], left: int, right: int,
key: int) -> int:
if left <= right:
if array[left] == key:
return left
else:
return binary_search_recursive(array, left + 1, right, key)
return -1
但它仍然不是二进制搜索。
编辑:
真正的二进制搜索应该是如下所示:
def binary_search_recursive(array: list[int], left: int, right: int,
key: int) -> int:
if right >= left:
center = (right + left) // 2
if array[center] == key:
return center
elif array[center] > key:
return binary_search_recursive(array, left, center - 1, key)
else:
return binary_search_recursive(array, center + 1, right, key)
return -1