Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def recursive_binary_search(array, target):
- return bs_helper(array, target, 0, len(array)-1)
- def bs_helper(array, target, left, right):
- if left > right:
- return -1
- middle = (left+right) // 2
- potential_match = array[middle]
- if target == potential_match:
- return middle
- elif target < potential_match:
- return binary_search_helper(array, target, left, middle - 1)
- else:
- return binary_search_helper(array, target, middle + 1, right)
- # Example usage
- arr = [1, 2, 3, 10, 40]
- print(recursive_binary_search(arr, 10)) # Output: 3
- print(recursive_binary_search(arr, 0)) # Output: -1
Advertisement
Add Comment
Please, Sign In to add comment