Searching
Binary Search (Recursive)
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
arras aconstArrayofNumbervalues and keepstargetin the outer scope; recursive calls pass only the numericloandhibounds. - The base case
lo > hireturns-1. Otherwise the frame computesconst mid = lo + Math.floor((hi - lo) / 2), readsarr[mid], and uses strict equality for the hit check. - Numeric comparison
arr[mid] < targetchoosessearch(mid + 1, hi)for the right half; the remaining branch returnssearch(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), computesmid=3witharr[mid]=7, and recurses right to(4, 6). The next frame computesmid=5, seesarr[mid]=11, and returns5. console.log(search(0, arr.length - 1))prints the numeric result5. 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.