nathanwailes

Binary search (recursive)

Mar 26th, 2024 (edited)
590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. def recursive_binary_search(array, target):
  2.     return bs_helper(array, target, 0, len(array)-1)
  3.  
  4. def bs_helper(array, target, left, right):
  5.     if left > right:
  6.         return -1
  7.     middle = (left+right) // 2
  8.     potential_match = array[middle]
  9.     if target == potential_match:
  10.             return middle
  11.     elif target < potential_match:
  12.         return binary_search_helper(array, target, left, middle - 1)
  13.     else:
  14.         return binary_search_helper(array, target, middle + 1, right)
  15.  
  16. # Example usage
  17. arr = [1, 2, 3, 10, 40]
  18. print(recursive_binary_search(arr, 10))  # Output: 3
  19. print(recursive_binary_search(arr, 0))  # Output: -1
Advertisement
Add Comment
Please, Sign In to add comment