From 256625afd77769b3c60acf1c53606fd654f5522c Mon Sep 17 00:00:00 2001 From: Yi-Jen Chen <89930807+yi-jenc@users.noreply.github.com> Date: Fri, 22 Mar 2024 21:06:55 +0100 Subject: [PATCH] fix recursive solution for binary search in python (#279) --- .../python/05_binary_search_recursive.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/03_recursion/python/05_binary_search_recursive.py b/03_recursion/python/05_binary_search_recursive.py index 3ed0b23..c6461d6 100644 --- a/03_recursion/python/05_binary_search_recursive.py +++ b/03_recursion/python/05_binary_search_recursive.py @@ -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))