Binary search in JavaScript
Intermediate · 4 min read
Think of looking up a word in a paper dictionary. You don't read from page one. You open it in 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 one of the most important ideas in programming.
In this tutorial you will write binarySearch for a sorted array of numbers. It finds an item in a list of 1,000 in about ten steps. You will also get the two boundary details right that most first attempts get wrong. You need to know arrays, while loops and Math.floor. The rest is explained as we go.
The one rule: the list must be sorted
Halving only works because the list is in order. If the middle item is smaller than what you want, everything to its left is smaller too, so you can skip it all. On an unsorted list that reasoning is false, and the search gives wrong answers without any error.
The plan, in words
Keep two markers, low and high, for the part of the list that might still hold the target. At first that is the whole list. Then repeat:
- Look at the middle item between
lowandhigh. - If it is the target, you're done.
- If it is smaller than the target, the target must be to the right, so move
lowpast the middle. - If it is bigger, move
highbefore the middle. - If
lowpasseshigh, nothing is left to check: the target is missing.
low=0 high=6 mid=3 value 7 too small, low = 4
low=4 high=6 mid=5 value 11 found at index 5
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
2 Binary search on a sorted list
fairSearch a sorted list by halving the range each time. Get the loop boundaries right, and note the overflow-safe way to find the midpoint.
Stuck? Three hints, smallest first
- 1. The list must already be sorted. Binary search on unsorted data returns nonsense, quietly.
- 2. Use
while (low <= high). With<you miss the case where the range is one element. - 3.
low + Math.floor((high - low) / 2)avoids an overflow that(low + high) / 2can cause in other languages.
Step 1: find the middle
The middle index between low and high is their average, rounded down. The answer writes it as low + Math.floor((high - low) / 2). That gives the same number as Math.floor((low + high) / 2):
const low = 4;
const high = 6;
console.log(low + Math.floor((high - low) / 2)); // 5
console.log(Math.floor((low + high) / 2)); // 5
In some other languages, adding two very large whole numbers can overflow, so programmers use the first form out of habit. It can't overflow in JavaScript, but the habit costs nothing.
Step 2: the loop
low starts at 0 and high at the last index. Each time round, compare the middle value with the target and move one marker:
function binarySearch(sorted, target) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
const value = sorted[mid];
if (value === target) return mid;
if (value < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
const sorted = [1, 3, 5, 7, 9, 11, 13];
console.log(binarySearch(sorted, 7)); // 3
console.log(binarySearch(sorted, 13)); // 6
console.log(binarySearch(sorted, 1)); // 0
console.log(binarySearch(sorted, 8)); // -1
low = mid + 1 and high = mid - 1 skip the middle, because we just checked it.
Step 3: why <= and not <
The natural wrong turn is while (low < high). Try it:
function wrong(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(wrong([42], 42)); // -1, but 42 is at index 0
console.log(wrong([1, 3, 5, 7], 7)); // -1, but 7 is at index 3
When the range shrinks to a single item, low equals high. That last item still has to be checked, and < skips it. With <=, one-item ranges get checked.
Step 4: the silent failure on unsorted data
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([9, 1, 7, 3], 7)); // 2
console.log(binarySearch([9, 1, 7, 3], 9)); // -1, but 9 is at index 0
Searching for 7 happens to land on the right index, by luck. Searching for 9 fails: the first middle value is 1, which is smaller than 9, so the search throws away the left half, where 9 really is. No error, just a wrong answer. Sort first, or use a linear search.
Step 5: count the steps
Each step halves what is left. 1,000 items become 500, 250, 125 and so on, reaching one item after about ten halvings. The answer counts the steps to find the last item of a 1,000-item list: 10. A linear search would need 1,000.
The full solution
The panel searches a sorted list for its first, middle, last and a missing value, runs it on an unsorted list, and counts the steps for 1,000 items. Press Run to see each line.
function binarySearch(sorted, target) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) { // <= , not < : the one-element range matters
// Written this way out of habit: in languages with fixed-width ints,
// (low + high) can overflow. It cannot here, but the habit is free.
const mid = low + Math.floor((high - low) / 2);
const value = sorted[mid];
if (value === target) return mid;
if (value < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
const sorted = [1, 3, 5, 7, 9, 11, 13];
for (const t of [1, 7, 13, 8]) {
console.log('looking for', t, '->', binarySearch(sorted, t));
}
// The silent failure: unsorted input gives a wrong answer, not an error.
const unsorted = [9, 1, 7, 3];
console.log('binary search on unsorted:', binarySearch(unsorted, 7), '(7 is really at index 2)');
// Count the steps, to show the halving.
function steps(n) {
const list = Array.from({ length: n }, (_, i) => i);
let count = 0;
let low = 0;
let high = n - 1;
while (low <= high) {
count++;
const mid = low + Math.floor((high - low) / 2);
if (list[mid] === n - 1) break;
if (list[mid] < n - 1) low = mid + 1;
else high = mid - 1;
}
return count;
}
console.log('steps to find the last of 1000:', steps(1000));
Output
10 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 10 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(sorted, 1), 0);
test('the middle', binarySearch(sorted, 7), 3);
test('the last element', binarySearch(sorted, 13), 6);
test('absent gives -1', binarySearch(sorted, 8), -1);
test('below the range', binarySearch(sorted, 0), -1);
test('above the range', binarySearch(sorted, 99), -1);
test('a single-element list finds its one value', binarySearch([42], 42), 0);
test('and reports a miss', binarySearch([42], 1), -1);
test('an empty list gives -1', binarySearch([], 1), -1);
test('1000 items take about ten steps', steps(1000) <= 10, true);
Two boundary details decide whether this is correct. while (low <= high) rather than <, because when the range narrows to a single element low equals high and that element still has to be checked — the single-element assertions cover it. And the unsorted example is the warning: binary search on unsorted input does not complain, it just returns the wrong answer.
Common mistakes
- Using
while (low < high). One-item ranges are never checked, so some items are never found. - Writing
low = midinstead ofmid + 1. Whenlowandmidare the same, the range stops shrinking and the loop never ends. - Searching unsorted data. It doesn't throw. It returns -1 or the wrong index. Sort the array first.
Try it yourself
- Search an array of names sorted alphabetically.
<compares strings too. - Add a counter and print how many steps it takes to find 13 in the list above.
- Make the search report the index of the first of several equal values, like the first 3 in
[1, 3, 3, 3, 7].