Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.

Algorithm

Basic Implementation

basic.js
const arr = [1, 3, 5, 7, 9, 11, 13];
const target = 11;

function search(lo, hi) {
  if (lo > hi) {
    return -1;
  }
  const mid = lo + Math.floor((hi - lo) / 2);
  if (arr[mid] === target) {
    return mid;
  }
  if (arr[mid] < target) {
    return search(mid + 1, hi);
  }
  return search(lo, mid - 1);
}

console.log(search(0, arr.length - 1));

Complexity

  • Time: O(log n)
  • Space: O(log n) call stack

Implementation notes

  • JavaScript stores arr as a const Array of Number values and keeps target in the outer scope; recursive calls pass only the numeric lo and hi bounds.
  • The base case lo > hi returns -1. Otherwise the frame computes const mid = lo + Math.floor((hi - lo) / 2), reads arr[mid], and uses strict equality for the hit check.
  • Numeric comparison arr[mid] < target chooses search(mid + 1, hi) for the right half; the remaining branch returns search(lo, mid - 1) for the left half. Each recursive call creates a normal JavaScript stack frame and returns the found index back to the caller.
  • The replay starts with search(lo=0, hi=6), computes mid=3 with arr[mid]=7, and recurses right to (4, 6). The next frame computes mid=5, sees arr[mid]=11, and returns 5.
  • console.log(search(0, arr.length - 1)) prints the numeric result 5. The search does not mutate or copy the array; it uses call-stack frames for recursion, and the only lesson-visible heap allocation is the input array.
execution replay The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison This JavaScript DSA version keeps the same data and final output as every other DSA book in this wave.