Recursive binary search
Easy TimeO(log n) SpaceO(log n) stack
Given an array arr sorted in ascending order, a target, and the low and high bounds of the region still being searched, return the target's index or -1. The bounds are inclusive, so a low above high is an empty region and means the target is absent.
Examples
Example 1
- Input
- arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]target = 23low = 0high = 12
- Output
- Thirteen odd values, and 23 is the twelfth of them — index 11.
11
Example 2
- Input
- arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]target = 4low = 0high = 12
- Output
- Every value here is odd, so 4 is absent.
-1
The Code
function binarySearch(arr, target, low, high) {
if (low > high) return -1;
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) return binarySearch(arr, target, mid + 1, high);
return binarySearch(arr, target, low, mid - 1);
}
binarySearch([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25], 23, 0, 12);Done
More like this
All searching examples (8) →- Binary search Halve the search range each step with lo / mid / hi.
- Linear search Scan left to right until you find the value.
- Rotated search Binary search where one half is always sorted — use it.
- Find peak Climb toward the higher neighbour — a peak must lie that way.
- Insert position Binary search that returns where a value *would* go.
- Search on the answer Binary search the answer space, not the array.