Write a binary search function in JavaScript
Intermediate · 4 min read
Think of looking 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. Repeat that a few times and you are on the right page. That is binary search, and it is how databases, autocomplete lists and many library functions find things fast.
In this tutorial you will write binarySearch(sorted, target), which returns the position of target in a sorted array, or -1 if it isn't there. You will see the one-character bug that breaks most first attempts, make the function search objects with a compare parameter, and find out what happens when the array isn't sorted. You need to know while loops and arrays.
Why halving is so fast
A normal search, like indexOf, checks every item from the start. For a list of a million items that can be a million checks. Binary search halves the range each time, so a million items take about 20 checks.
There is one condition: the array must already be sorted. Halving only works if "smaller" values are always on the left.
The two boundaries
The search keeps two positions, low and high, marking the part of the array where the target could still be. At the start that is the whole array:
const numbers = [1, 3, 5, 7, 9, 11, 13];
const low = 0;
const high = numbers.length - 1;
console.log(low, high); // 0 6
console.log(low + Math.floor((high - low) / 2)); // 3
The middle of that range is position 3, which holds 7.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
18 Binary search in an array
fairSearch a sorted array by halving the range. Return the index, and handle the case where the array is not sorted.
Stuck? Three hints, smallest first
- 1. The array must already be sorted, or the answer is silently wrong.
- 2.
while (low <= high), not<, or the one-element range is skipped. - 3. A comparator parameter lets it search objects, not only numbers.
Step 1: one look at the middle
Compare the middle value with the target. There are three outcomes:
- They are equal: found it, return the middle position.
- The middle value is smaller: the target must be to the right, so move
lowtomid + 1. - The middle value is bigger: the target must be to the left, so move
hightomid - 1.
The + 1 and - 1 matter: the middle has already been checked, so it is left out of the next range.
Step 2: loop until the range is empty
Repeat that while there is still something in the range:
function firstTry(sorted, target) {
let low = 0;
let high = sorted.length - 1;
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
console.log(firstTry([1, 3, 5, 7, 9, 11, 13], 7)); // 3
console.log(firstTry([1, 3, 5, 7, 9, 11, 13], 13)); // -1
console.log(firstTry([42], 42)); // -1
7 is found. But 13 is right there at the end, and [42] doesn't find 42. This is the classic bug.
Step 3: <= not <
When low and high are equal, the range still has one item in it. while (low < high) stops before checking it. For [42], low and high are both 0 from the start, so the loop never runs. Use <=:
function binarySearch(sorted, target) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
console.log(binarySearch([1, 3, 5, 7, 9, 11, 13], 13)); // 6
console.log(binarySearch([42], 42)); // 0
console.log(binarySearch([1, 3, 5, 7, 9, 11, 13], 8)); // -1
When the target is missing, low ends up past high, the range is empty, and the function returns -1.
Step 4: a compare parameter
Right now the function can only compare with < and ===, which suits numbers. To search a list of objects, let the caller pass a compare function. It takes two values and returns a negative number if the first comes earlier, a positive one if it comes later, and 0 if they match. The default, (a, b) => a - b, does that for numbers:
function binarySearchBy(sorted, target, compare = (a, b) => a - b) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
const order = compare(sorted[mid], target);
if (order === 0) return mid;
if (order < 0) low = mid + 1;
else high = mid - 1;
}
return -1;
}
const buses = [{ plate: 'ABJ-772-KM' }, { plate: 'ENU-318-PH' }, { plate: 'LAG-441-XA' }];
const byPlate = (a, b) => a.plate.localeCompare(b, 'en');
console.log(binarySearchBy(buses, 'ENU-318-PH', byPlate)); // 1
console.log(binarySearchBy([1, 3, 5], 5)); // 2
localeCompare returns exactly the negative, zero or positive number that compare needs. The buses are sorted by plate, so the search works on them with no change to the loop. In the full answer this is the only version, called binarySearch; its byPlate also accepts a whole bus object as the target.
Step 5: what if the array isn't sorted?
const unsorted = [9, 1, 7, 3];
console.log(binarySearchBy(unsorted, 9)); // -1
console.log(unsorted.indexOf(9)); // 0
No error, just a wrong answer. The search looked at the middle, saw 1, decided 9 must be on the right, and never looked at position 0. Worse, for some targets it gets lucky and returns the right answer, so the bug is easy to miss.
The answer adds safeBinarySearch, which first checks the array is sorted with every and throws a TypeError if it isn't. That check reads the whole array, which removes the speed advantage, so it belongs at the point where the data arrives, not inside a loop of searches.
The full solution
The panel has binarySearch with its compare parameter, isSorted and safeBinarySearch. It searches for four numbers, finds a bus by plate, then shows the unsorted array giving a wrong answer and the safe version refusing it. Press Run to see the output.
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) { // <= : the one-element range matters
const mid = low + Math.floor((high - low) / 2);
const order = compare(sorted[mid], target);
if (order === 0) return mid;
if (order < 0) low = mid + 1;
else high = mid - 1;
}
return -1;
}
// Refuse unsorted input rather than returning a wrong answer quietly.
const isSorted = (a, compare = (x, y) => x - y) => a.every((v, i) => i === 0 || compare(a[i - 1], v) <= 0);
function safeBinarySearch(sorted, target, compare) {
if (!isSorted(sorted, compare)) throw new TypeError('binary search needs a sorted array');
return binarySearch(sorted, target, compare);
}
const numbers = [1, 3, 5, 7, 9, 11, 13];
const buses = [
{ plate: 'ABJ-772-KM', seats: 30 },
{ plate: 'ENU-318-PH', seats: 7 },
{ plate: 'LAG-441-XA', seats: 14 },
];
const byPlate = (a, b) => a.plate.localeCompare(typeof b === 'string' ? b : b.plate, 'en');
for (const t of [1, 7, 13, 8]) console.log('looking for', String(t).padEnd(3), '->', binarySearch(numbers, t));
console.log('searching objects by plate:', binarySearch(buses, 'ENU-318-PH', byPlate));
console.log('--- unsorted input ---');
const unsorted = [9, 1, 7, 3];
console.log('plain search on unsorted for 9:', binarySearch(unsorted, 9), '(9 is really at index 0)');
console.log('and for 7 it happens to be right:', binarySearch(unsorted, 7), '<- luck, not correctness');
const refused = (() => { try { safeBinarySearch(unsorted, 7); return 'no error'; } catch (e) { return e.constructor.name; } })();
console.log('safe version:', refused);
Output
21 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 21 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first element', binarySearch(numbers, 1), 0);
test('the middle', binarySearch(numbers, 7), 3);
test('the last', binarySearch(numbers, 13), 6);
test('an absent value gives -1', binarySearch(numbers, 8), -1);
test('below the range', binarySearch(numbers, 0), -1);
test('above the range', binarySearch(numbers, 99), -1);
test('an empty array', binarySearch([], 1), -1);
test('a single element, found', binarySearch([42], 42), 0);
test('a single element, missed', binarySearch([42], 1), -1);
test('every element is found at its own index', numbers.every((v, i) => binarySearch(numbers, v) === i), true);
test('it agrees with indexOf throughout', numbers.every((v) => binarySearch(numbers, v) === numbers.indexOf(v)), true);
test('a comparator lets it search objects', binarySearch(buses, 'ENU-318-PH', byPlate), 1);
test('and miss cleanly', binarySearch(buses, 'KAN-905-BD', byPlate), -1);
test('unsorted input gives a WRONG answer, not an error', binarySearch(unsorted, 9), -1);
test('even though 9 is right there at index 0', unsorted.indexOf(9), 0);
test('and on other targets it can be right by luck', binarySearch(unsorted, 7), unsorted.indexOf(7));
test('which is what makes the bug hard to spot', binarySearch(unsorted, 9) === unsorted.indexOf(9), false);
test('which is why the safe version refuses it', refused, 'TypeError');
test('the sorted check accepts sorted input', isSorted(numbers), true);
test('and rejects unsorted', isSorted(unsorted), false);
test('duplicates are still sorted', isSorted([1, 1, 2]), true);
Searching 2 covers the algorithm; the angle here is the function's interface. A compare parameter with a default turns a numbers-only search into one that works on objects — the assertion searching buses by plate uses the same function body.
The other addition is refusing bad input. Binary search on an unsorted array does not throw; it returns a confidently wrong index, and the assertion showing it disagreeing with indexOf is the proof. safeBinarySearch checks first and throws, which costs O(n) and so defeats the point if you call it in a loop — the honest position is to validate once at the boundary where the data arrives, not on every search.
Common mistakes
- Writing
while (low < high). The last one-item range is never checked, so the first or last element and one-item arrays are missed. - Setting
low = midorhigh = mid. The range can stop shrinking, and the loop runs forever. Usemid + 1andmid - 1. - Searching an unsorted array. You get a confident wrong answer, not an error. Sort first, or check once when the data arrives.
Try it yourself
- Add a counter and check how many times the loop runs to find 13 in
[1, 3, 5, 7, 9, 11, 13]. - Search an array of 1,000 numbers made with
Array.from({ length: 1000 }, (_, i) => i * 2)and count the steps. - Sort
[9, 1, 7, 3]withsort((a, b) => a - b)and search it again for 9.