Recursive binary search returning the index in JavaScript
Intermediate · 4 min read
Binary search finds an item in a sorted list by checking the middle, throwing away the half that can't hold it, and repeating. It is the reason a sorted list of a million names can be searched in about 20 steps. Most real searches need more than "yes, it's there": they need where it is, so the program can read it, update it or delete it.
In this tutorial you will write binarySearch(sorted, target) recursively so that it returns the item's position, or -1 when it isn't there. Unlike the slicing version, it never copies the array. You need to know arrays, indexes and functions. Recursion is explained below.
Bounds instead of slices
Cutting the array with slice makes a new, smaller array at every step, and every new array counts its positions from 0 again. So the position you find is a position in the copy, not in the original list.
The fix is to leave the array alone and track the part still being searched with two numbers: low, the first index that could hold the target, and high, the last. Each step moves one of them toward the other. When low passes high, there's nothing left to search.
Recursion in one paragraph
A recursive function calls itself on a smaller version of the problem. Here each call searches a range about half the size of the last one. It stops at a base case: an empty range, which means the target isn't in the list.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
12 Recursive binary search returning an index
fairSame search as exercise 8, but return the position and do no copying. The test data: searching for 6 gives 4, and searching for 16 gives −1.
Stuck? Three hints, smallest first
- 1. Pass
lowandhighinstead of slicing, so the indexes stay meaningful. - 2. The empty case is
low > high, and it returns-1. - 3. Give the bounds default values so the caller does not have to supply them.
Step 1: default bounds
The first call should search the whole array, so give low and high default values. A default is used when the caller leaves that argument out:
function showBounds(sorted, low = 0, high = sorted.length - 1) {
return [low, high];
}
const data = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
console.log(showBounds(data)); // [ 0, 14 ]
console.log(showBounds(data, 5, 9)); // [ 5, 9 ]
The caller writes binarySearch(data, 6) and never has to think about bounds. The recursive calls pass their own.
Step 2: the base case and the middle
If low > high, the range is empty and the answer is -1. Otherwise, find the middle index of the range and check it:
function binarySearch(sorted, target, low = 0, high = sorted.length - 1) {
if (low > high) return -1;
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
return 'not done yet';
}
const data = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
console.log(binarySearch(data, 11)); // 7
console.log(binarySearch([], 1)); // -1
low + Math.floor((high - low) / 2) is the middle of the range. It equals Math.floor((low + high) / 2). In languages with fixed-size whole numbers, low + high can overflow on huge arrays, so many programmers write it this way out of habit. It costs nothing in JavaScript.
For an empty array, high starts at -1, which is less than low, so the base case catches it at once.
Step 3: recurse into one half
If the middle item is too small, the target can only be to the right, so the new range starts at mid + 1. If it is too big, the range ends at mid - 1:
function binarySearch(sorted, target, low = 0, high = sorted.length - 1) {
if (low > high) return -1;
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
return sorted[mid] < target
? binarySearch(sorted, target, mid + 1, high)
: binarySearch(sorted, target, low, mid - 1);
}
const data = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
console.log(binarySearch(data, 6)); // 4
console.log(binarySearch(data, 16)); // -1
console.log(binarySearch(data, 1)); // 0
console.log(binarySearch(data, 23)); // 14
Here is the search for 6:
low 0, high 14: mid 7 holds 11, too big -> high = 6
low 0, high 6: mid 3 holds 5, too small -> low = 4
low 4, high 6: mid 5 holds 7, too big -> high = 4
low 4, high 4: mid 4 holds 6, found -> 4
And for 16, the range shrinks until low is 10 and high is 9. They've crossed, so the answer is -1.
The + 1 and - 1 matter. The middle has been checked already, so leave it out. Using mid instead can keep the same range forever.
Step 4: count the calls
Count how many calls it takes to find the last item:
let calls = 0;
function counted(sorted, target, low = 0, high = sorted.length - 1) {
calls++;
if (low > high) return -1;
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
return sorted[mid] < target
? counted(sorted, target, mid + 1, high)
: counted(sorted, target, low, mid - 1);
}
const data = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
counted(data, 23);
console.log(calls); // 4
Four calls for 15 items. Checking one by one from the start would take 15. Every time the list doubles in size, binary search needs just one more step.
The full solution
The panel has the recursive search, the call counter and checks for both test cases, the first and last items, values outside the range, and agreement with indexOf for every item. Press Run to see the output.
function binarySearch(sorted, target, low = 0, high = sorted.length - 1) {
if (low > high) return -1; // the range is empty: not here
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
return sorted[mid] < target
? binarySearch(sorted, target, mid + 1, high)
: binarySearch(sorted, target, low, mid - 1);
}
// Count the calls, to show it is log2(n) and not n.
let calls = 0;
function counted(sorted, target, low = 0, high = sorted.length - 1) {
calls++;
if (low > high) return -1;
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
return sorted[mid] < target
? counted(sorted, target, mid + 1, high)
: counted(sorted, target, low, mid - 1);
}
const data = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
counted(data, 23);
console.log("looking for 6 ->", binarySearch(data, 6), "(expected: 4)");
console.log('looking for 16 ->', binarySearch(data, 16), '(expected: -1)');
console.log('15 items, calls to find the last one:', calls);
console.log('a linear scan would need:', data.length);
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the first case", binarySearch(data, 6), 4);
test("the second case", binarySearch(data, 16), -1);
test('the first element', binarySearch(data, 1), 0);
test('the last element', binarySearch(data, 23), 14);
test('below the range', binarySearch(data, 0), -1);
test('above the range', binarySearch(data, 99), -1);
test('an empty array', binarySearch([], 1), -1);
test('every element is found at its real index', data.every((v, i) => binarySearch(data, v) === i), true);
test('it agrees with indexOf throughout', data.every((v) => binarySearch(data, v) === data.indexOf(v)), true);
test('15 items need at most 4 comparisons', calls <= 4, true);
test('the array is never copied or changed', data.length, 15);
Carrying low and high instead of slicing is the difference between O(log n) extra memory and O(n log n). It also fixes the flaw in exercise 8: because no slice is taken, mid is a real index into the original array, so it can be returned directly. low + Math.floor((high - low) / 2) rather than (low + high) / 2 is a habit borrowed from languages with fixed-width integers, where the sum can overflow. It cannot here, and it costs nothing.
Common mistakes
- Writing
low >= highas the base case. A range with one item haslow === high, so the last candidate never gets checked. - Recursing with
midinstead ofmid + 1ormid - 1. The range can stop shrinking and the function never finishes. - Searching an unsorted array. The halving only makes sense when the items are in order. Sort first, or use
indexOf.
Try it yourself
- Rewrite
binarySearchas awhileloop that updateslowandhigh. - Change it to return the position where a missing target would go, so searching for 16 gives 10.
- Make a sorted array of 1,000 numbers with
Array.fromand count the calls to find its last item.