fix recursive solution for binary search in python (#279)

This commit is contained in:
Yi-Jen Chen
2024-03-22 21:06:55 +01:00
committed by GitHub
parent cfb59254fb
commit 256625afd7

View File

@@ -1,17 +1,20 @@
def binary_search(arr, target):
if not arr:
return -1
if len(arr) == 0:
return None
low = 0
high = len(arr) - 1
mid = (low + high) // 2
mid = len(arr) // 2
if arr[mid] == target:
return target
return mid
elif arr[mid] > target:
return binary_search(arr[:mid], target)
else:
return binary_search(arr[mid+1:], target)
recursive_response = binary_search(arr[(mid + 1) :], target)
return (
(mid + 1) + recursive_response
if recursive_response is not None
else recursive_response
)
print(binary_search([6, 7, 8, 9, 10], 8))