Recursive binary search with slicing in JavaScript
Intermediate · 3 min read
Think about how you look up a word in a paper dictionary. You don't start at page one. You open it near the middle, see whether your word comes before or after, and throw away the half it can't be in. A few more halvings and you're there. That is binary search, and it is how computers find things fast in sorted data.
In this tutorial you will write binary search as a recursive function that cuts the array in half with slice and searches the half that could hold the target. It returns the value it found, or null. You need to know arrays, indexes and functions. Recursion is explained below.
Why the array must be sorted
Binary search only works if the items are in order. In [0, 1, 2, 3, 4, 5, 6], if the middle item is 3 and you want 5, every item to the left of 3 is smaller, so 5 can only be on the right. In an unsorted array, that reasoning falls apart.
Recursion in one paragraph
A recursive function solves a problem by calling itself on a smaller version of it. Here each call searches half as many items. It stops at a base case: an empty array, where the target can't possibly be.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 Binary search over a shrinking slice
fairSearch a sorted array by cutting it in half and recursing into the half that could contain the target. The sample is [0,1,2,3,4,5,6] searching for 5.
Stuck? Three hints, smallest first
- 1. Cut with
slice, and remember that a slice loses the original indexes. - 2. The sample array has value equal to index at every position, so it cannot tell you which of the two is being returned.
- 3. Return the value found, or
null. Exercise 12 returns the index instead.
Step 1: find the middle
Math.floor rounds down, so for an array of 7 items the middle index is 3:
const sample = [0, 1, 2, 3, 4, 5, 6];
const mid = Math.floor(sample.length / 2);
console.log(mid); // 3
console.log(sample[mid]); // 3
For an even length like 6, it picks index 3, the first item of the right half. Either middle works.
Step 2: cut with slice
slice(start, end) copies part of an array, from start up to but not including end. Leave out end to go to the finish:
const sample = [0, 1, 2, 3, 4, 5, 6];
console.log(sample.slice(0, 3)); // [ 0, 1, 2 ]
console.log(sample.slice(4)); // [ 4, 5, 6 ]
console.log(sample); // [ 0, 1, 2, 3, 4, 5, 6 ]
The middle item, index 3, is in neither half, because it has already been checked. The original array is left untouched.
Step 3: the recursive search
Put it together. Check the empty case, check the middle, then search the right half or the left half:
function search(sorted, target) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
if (sorted[mid] === target) return sorted[mid];
return sorted[mid] < target
? search(sorted.slice(mid + 1), target)
: search(sorted.slice(0, mid), target);
}
const sample = [0, 1, 2, 3, 4, 5, 6];
console.log(search(sample, 5)); // 5
console.log(search(sample, 0)); // 0
console.log(search(sample, 99)); // null
console.log(search([], 1)); // null
Here is the search for 5:
[0, 1, 2, 3, 4, 5, 6] middle is 3, too small: go right
[4, 5, 6] middle is 5, found it
When the target isn't there, the halves keep shrinking until one is empty, and the base case returns null.
Step 4: value or index?
Look at the sample again. In [0, 1, 2, 3, 4, 5, 6], the value at index 5 is also 5. So the expected answer 5 can't tell you whether the function returns the value or the position. Test with an array where they differ:
function search(sorted, target) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
if (sorted[mid] === target) return sorted[mid];
return sorted[mid] < target
? search(sorted.slice(mid + 1), target)
: search(sorted.slice(0, mid), target);
}
const shifted = [10, 20, 30, 40, 50, 60, 70];
console.log(search(shifted, 50)); // 50, not the index 4
This version returns the value. It couldn't easily return the index, because every slice starts counting from 0 again. Inside [4, 5, 6], the 5 sits at index 1, not 5.
Step 5: count the copies
Each slice is a new array. Count how many get made while looking for the last item:
let slices = 0;
function searchCounted(sorted, target) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
if (sorted[mid] === target) return sorted[mid];
slices++;
return sorted[mid] < target
? searchCounted(sorted.slice(mid + 1), target)
: searchCounted(sorted.slice(0, mid), target);
}
searchCounted([0, 1, 2, 3, 4, 5, 6], 6);
console.log(slices); // 2
Two copies for seven items is cheap. On large arrays, all that copying is wasted work, which is what the index-based version avoids.
The full solution
The panel has the slicing search, a copy counter and checks for the first, last, missing and single-item cases, plus the shifted array that proves a value comes back. Press Run to see the output.
// Recursion by slicing. Simple to read, and it copies at every level.
function search(sorted, target) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
if (sorted[mid] === target) return sorted[mid];
return sorted[mid] < target
? search(sorted.slice(mid + 1), target) // right half
: search(sorted.slice(0, mid), target); // left half
}
// Count the arrays allocated, since that is the cost being hidden.
let slices = 0;
function searchCounted(sorted, target) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
if (sorted[mid] === target) return sorted[mid];
slices++;
return sorted[mid] < target
? searchCounted(sorted.slice(mid + 1), target)
: searchCounted(sorted.slice(0, mid), target);
}
const sample = [0, 1, 2, 3, 4, 5, 6];
searchCounted(sample, 6);
// Why the sample is ambiguous: here value and index are the same number.
const shifted = [10, 20, 30, 40, 50, 60, 70];
console.log("search(sample, 5) =", search(sample, 5), "<- the expected '5'");
console.log('but in this array value and index differ:');
console.log('search(shifted, 50) =', search(shifted, 50), '(index would be 4)');
console.log('missing target :', search(sample, 99));
console.log('arrays copied looking for 6:', slices);
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 example finds 5", search(sample, 5), 5);
test('the first element', search(sample, 0), 0);
test('the last element', search(sample, 6), 6);
test('a missing target gives null', search(sample, 99), null);
test('an empty array gives null', search([], 1), null);
test('one element, found', search([42], 42), 42);
test('one element, missed', search([42], 1), null);
test('it returns the value, not the index', search(shifted, 50), 50);
test('every element of a bigger array is findable', [1, 3, 5, 7, 9, 11, 13, 15].every((v, _, a) => search(a, v) === v), true);
test('slicing really does copy', slices > 0, true);
test('the input is untouched', sample, [0, 1, 2, 3, 4, 5, 6]);
The sample array is [0,1,2,3,4,5,6] and it expects 5 — but in that array the value at index 5 is 5, so the example cannot tell you whether the answer is the value or the position. That is why the assertions here also run against [10,20,…], where the two differ. Slicing is the readable way to recurse and it copies an array per level; exercise 12 does the same search with index bounds and no copying at all.
Common mistakes
- Searching unsorted data. Binary search assumes order. On
[5, 1, 4]it can miss items that are there. - Including the middle in a half.
slice(mid)instead ofslice(mid + 1)can keep a one-item array forever and never reach the base case. - Expecting an index back. After slicing, positions restart at 0. Use the low and high bounds approach when you need the index.
Try it yourself
- Change
searchto returntrueorfalseinstead of the value. - Search an array of words sorted alphabetically, like
['ada', 'bode', 'chidi', 'dele']. Does<work on strings? - Count the slices when searching for a missing value in an array of 100 sorted numbers.