Problem 38

Binary Search Recursion Challenge

Given a sorted array of integers and a target value, return the index of the target using binary search. If the target is not found, return null.

Function Signature

binarySearch(array, target, min, max)

Parameters

  • array — a sorted array of integers.
  • target — the integer to search for.
  • min — (optional) the lower bound index, defaults to 0.
  • max — (optional) the upper bound index, defaults to array.length - 1.

Output

Return the index of the target in the array, or null if not found.

Constraints

  • The function must use recursion.
  • The input array must not be mutated.
  • The function should accept at most four arguments.

Examples

binarySearch([1, 2, 3, 4, 5, 6], 4)  → 3
binarySearch([1, 2, 3, 4, 5, 6], 6)  → 5
binarySearch([1, 2, 3, 4, 5, 6], 7)  → null
binarySearch([-5, -4, -3, -2, -1], -3) → 2
binarySearch([2, 3, 5, 7, 11, 13], 32) → null