我需要撰寫一個簡單的遞回函式,從索引:左到索引:右搜索陣列。我們不必擔心無效的左右輸入,它們總是正確的。如果陣列中有一個等于鍵的值,則回傳該值的索引。如果鍵不在陣列中,則回傳-1.
我真的不知道為什么我的函式不起作用。我認為應該。僅當鍵是陣列的第一個索引時才有效。
def binary_search_recursive(array: List[int], left: int, right: int,
key: int) -> int:
if left <= right:
if array[left] == key:
return left
else:
binary_search_recursive(array, left 1, right, key)
return -1
測驗:
binary_search_recursive([0,1,5,6,23,45], 0, 5, 5)
應該回傳:
2
回報:
-1
uj5u.com熱心網友回復:
要修復您的代碼,您需要回傳 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
uj5u.com熱心網友回復:
您需要將遞回呼叫的結果回傳到binary_search_recursive():
binary_search_recursive(array, left 1, right, key)
應該
return binary_search_recursive(array, left 1, right, key)
請注意,這不是二進制搜索演算法;您一次列舉一個元素(使用遞回),所以這實際上是一個順序搜索。
uj5u.com熱心網友回復:
您需要在第二次回傳中使用制表符。嘗試:
key: int) -> int:
if left <= right:
if array[left] == key:
return left
else:
binary_search_recursive(array, left 1, right, key)
return -1 #Moved to the right.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448944.html
上一篇:計算遞回呼叫的次數
下一篇:在C中的另一個函式內定義遞回函式
