Emmanuel Akinfulubi

JavaScriptArray

Binary search vs linear search in JavaScript

Advanced · 4 min read

Finding a value in an array is something programs do constantly. The simple way, called linear search, checks every item from the start until it finds a match. Binary search is much faster, but it only works on a sorted array. It is how you look up a word in a paper dictionary: open in the middle, see which half the word is in, and repeat.

In this tutorial you will write binarySearch, count how many comparisons it makes, and compare that with a linear scan over 1,024 values. You will also see the two ways it goes wrong: an off-by-one loop condition, and unsorted input. You should know arrays, while loops and Math.floor.

Linear search

indexOf is a linear search. It reads items one by one, so the worst case reads all of them:

JavaScript

const evens = Array.from({ length: 1024 }, (_, i) => i * 2);

console.log(evens.slice(0, 4)); // [ 0, 2, 4, 6 ]
console.log(evens.indexOf(2046)); // 1023

evens holds 0, 2, 4 and so on up to 2046. The last value sits at index 1023, so indexOf had to read 1,024 items to find it.

Halving

Binary search keeps a range of indexes where the value could still be, from low to high. Each round it looks at the middle item:

  • If it's the target, done.
  • If it's smaller than the target, the target must be to the right, so move low past the middle.
  • If it's bigger, move high before the middle.

Each round throws away half of what's left. 1,024 halves to 512, then 256, and after about ten rounds only one item remains. That is why it needs a sorted array: "smaller means look right" is only true when the values are in order.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

51 Binary search, and what it costs

hard

Search a sorted array by halving the range, and count the comparisons. Compare that with a linear scan over 1024 values, then run it on unsorted input.

Stuck? Three hints, smallest first
  1. 1. while (low <= high), not <: when the range narrows to one element, low equals high and that element still needs checking.
  2. 2. The midpoint must be floored, or the index is not an integer.
  3. 3. The array must already be sorted. Nothing in the algorithm can detect that it is not.

Step 1: the range and the middle

Step 1

const sorted = [10, 20, 30, 40, 50];
let low = 0;
let high = sorted.length - 1;
const mid = Math.floor((low + high) / 2);

console.log(low, high, mid, sorted[mid]); // 0 4 2 30

The range starts as the whole array, from index 0 to the last index. The middle is the average of the two ends, rounded down with Math.floor. Without rounding, a range like 0 to 3 would give 1.5, which isn't an index.

Step 2: the loop

Step 2

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let comparisons = 0;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    comparisons++;
    if (sorted[mid] === target) return { index: mid, comparisons };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, comparisons };
}

console.log(binarySearch([10, 20, 30, 40, 50], 40)); // { index: 3, comparisons: 2 }
console.log(binarySearch([10, 20, 30, 40, 50], 35)); // { index: -1, comparisons: 2 }

For 40: the middle is 30, which is smaller, so low becomes 3. The new middle is index 3, which holds 40. Two comparisons.

low = mid + 1 and high = mid - 1 skip the middle, because it has just been checked. When low passes high, the range is empty and the value isn't there, so the function returns -1, the same "not found" signal indexOf uses. It also returns the comparison count, so you can see the cost.

Step 3: the off-by-one trap

The loop condition is low <= high, not low < high. Here is what the second one does:

Step 3

function lessThan(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return mid;
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}

console.log(lessThan([42], 42));                 // -1
console.log(lessThan([10, 20, 30, 40, 50], 50)); // -1

With one item, low and high are both 0. 0 < 0 is false, so the loop never runs and the one item is never checked. The same thing happens at the end of a longer search, whenever the range narrows to a single item. With <=, a one-item range still gets its look.

Step 4: count the cost

Step 4

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let comparisons = 0;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    comparisons++;
    if (sorted[mid] === target) return { index: mid, comparisons };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, comparisons };
}

const evens = Array.from({ length: 1024 }, (_, i) => i * 2);
console.log(binarySearch(evens, 500));  // { index: 250, comparisons: 10 }
console.log(binarySearch(evens, 2046)); // { index: 1023, comparisons: 11 }
console.log(binarySearch(evens, 501));  // { index: -1, comparisons: 10 }
console.log(evens.indexOf(2046) + 1);   // 1024
console.log(2 ** 11);                   // 2048

Eleven comparisons at most, against 1,024 reads for a linear scan. 2 ** 11 is 2 to the power of 11, which is 2,048. Eleven halvings are enough to get from 1,024 items down to one, with room to spare. Double the data and binary search needs just one more comparison.

That said, for a few hundred items indexOf is often the better choice. It is already written, it works on any array, and it doesn't need the data kept in order.

Step 5: unsorted input

Step 5

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let comparisons = 0;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    comparisons++;
    if (sorted[mid] === target) return { index: mid, comparisons };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, comparisons };
}

const unsorted = [5, 1, 9];
console.log(binarySearch(unsorted, 5).index); // -1
console.log(unsorted.indexOf(5));             // 0

5 is right there at index 0, yet binary search says "not found". The middle item is 1, which is smaller than 5, so the search moves right and never looks at the left side again. There is no error and no warning. The function can't check that its input is sorted without reading every item, which is the very work it exists to avoid. Keeping the array sorted is your job.

The full solution

The panel builds the 1,024 even numbers, searches for a value in the middle, one that's missing and the last one, then runs the search on unsorted input. Press Run and compare the comparison counts with the linear scan.

The answer

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let comparisons = 0;

  while (low <= high) {                       // <= , or a one-element range is skipped
    const mid = Math.floor((low + high) / 2);
    comparisons++;
    if (sorted[mid] === target) return { index: mid, comparisons };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, comparisons };
}

const evens = Array.from({ length: 1024 }, (_, i) => i * 2);
const unsorted = [5, 1, 9];

console.log('find 500      :', binarySearch(evens, 500));
console.log('find 501      :', binarySearch(evens, 501), '<- not present');
console.log('find the last :', binarySearch(evens, 2046));
console.log('a linear scan would have taken', evens.indexOf(2046) + 1, 'reads');
console.log('2 ** 11 =', 2 ** 11, 'which is why 11 comparisons cover 1024 values');
console.log('--- unsorted input ---');
console.log('binarySearch([5,1,9], 5):', binarySearch(unsorted, 5).index, '<- wrong, and it does not complain');
console.log('indexOf says             :', unsorted.indexOf(5));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('it finds a value and reports the index', binarySearch(evens, 500).index, 250);
test('in ten comparisons out of 1024 values', binarySearch(evens, 500).comparisons, 10);
test('the last element takes eleven', binarySearch(evens, 2046).comparisons, 11);
test('where a linear scan needs 1024 reads', evens.indexOf(2046) + 1, 1024);
test('a miss is -1', binarySearch(evens, 501).index, -1);
test('a single-element array is searched, not skipped', binarySearch([42], 42).index, 0);
test('and reports a miss on it too', binarySearch([42], 1).index, -1);
test('an empty array makes no comparisons at all', binarySearch([], 1), { index: -1, comparisons: 0 });
test('unsorted input gives a wrong answer, silently', [binarySearch(unsorted, 5).index, unsorted.indexOf(5)], [-1, 0]);

Also Searching 2 and Function 18, which derive the algorithm. The angle here is the cost, because that is the only reason to write it: eleven comparisons instead of 1024 reads, and each doubling of the data adds one comparison. Below a few hundred elements indexOf is the better choice — it needs no sorted input, no maintenance, and no correctness argument.

Two failure modes are worth carrying. while (low < high) silently never checks a one-element range, which the [42] assertions catch. And unsorted input produces a confident wrong answer: the last assertion shows the search reporting "not found" for a value sitting at index 0. If the sortedness is an assumption, make it an invariant somewhere else — the search cannot check it without doing the linear scan it exists to avoid.

Common mistakes

  • Looping while low < high. A one-item range is never checked, so [42] doesn't find 42. Use <=.
  • Forgetting Math.floor on the middle. (0 + 3) / 2 is 1.5, and sorted[1.5] is undefined.
  • Searching an unsorted array. The answer is silently wrong. Sort first, or use indexOf.

Try it yourself

  1. Change binarySearch to return the index where the target would go when it's missing.
  2. Search 1,000,000 sorted numbers and print how many comparisons the worst case takes.
  3. Write a version for an array sorted from largest to smallest.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.