Emmanuel Akinfulubi

JavaScriptBasic

Binary search and the infinite loop bug in JavaScript

Advanced · 5 min read

Think about finding a word in a paper dictionary. You don't start on page one and read every word. You open it near the middle, see whether your word comes before or after, and throw away half the book. Then you do the same with the half that is left. That idea is called binary search, and it is one of the fastest ways to find something in a sorted list.

In this tutorial you will write search, which finds a value in a sorted array, counts its steps, and tells you where a missing value would go. Then you'll see the tiny mistake that makes binary search run for ever, and what happens when the array is not sorted. You need to know while loops, array indexes and Math.floor.

The idea: halve the range every time

Play the number guessing game: someone picks a number from 1 to 100, and after each guess they say "higher" or "lower". Guess 50 first. Whatever they answer, half the numbers are gone. Guess the middle of what is left, and half of that is gone too.

Each guess halves the range, so the number of guesses grows very slowly:

JavaScript

console.log(2 ** 7);  // 128: seven guesses cover 1 to 100
console.log(2 ** 10); // 1024: ten guesses cover a thousand items
console.log(2 ** 20); // 1048576: twenty cover a million

** means "to the power of". Looking at every item one by one is called a linear scan, and for the last of a thousand items it compares a thousand times. Binary search needs ten.

The one rule: the array must be sorted

"Higher" and "lower" only mean something if the items are in order. Binary search trusts that order completely. Give it an unsorted array and it doesn't get slow, it gets wrong. We'll prove that at the end.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

142 Binary search, and the version that never stops

hard

Find a value in a sorted array by halving the range each time. Report where it is, or where it would go if it is missing, and count the steps. Then show what happens when the range is narrowed to mid instead of mid + 1, and what happens on an array that is not sorted.

Stuck? Three hints, smallest first
  1. 1. Two markers, low and high, and a loop that runs while low is not past high.
  2. 2. If the middle is too small, the answer is above it: low becomes mid + 1, not mid.
  3. 3. When the loop ends without a hit, low is exactly the index the value would be inserted at.

Step 1: two markers and a middle

We keep two indexes, low and high, that mark the part of the array still worth looking at. At the start, that's the whole array.

Step 1

const sorted = [1, 3, 5, 7, 9, 11, 13];
const low = 0;
const high = sorted.length - 1;
const mid = Math.floor((low + high) / 2);
console.log(low, high, mid); // 0 6 3
console.log(sorted[mid]);    // 7

mid is the index halfway between them. Math.floor rounds down, because an index must be a whole number: with low 0 and high 5, the halfway point is 2.5, and we use 2.

Step 2: the loop

Now compare the middle item with the target and move one of the markers:

Step 2

function search(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(search([1, 3, 5, 7, 9, 11, 13], 11)); // 5
console.log(search([1, 3, 5, 7, 9, 11, 13], 4));  // -1

Follow the search for 11. First mid is 3, and sorted[3] is 7. That's too small, so 11 must be to the right: low becomes 4. Now mid is 5, sorted[5] is 11, and we return 5.

The loop runs while low <= high. When they are equal, one item is left and it still needs checking. When low moves past high, nothing is left, so the value isn't there and we return -1.

Step 3: the wrong turn, mid instead of mid + 1

Here's the line people get wrong. Once sorted[mid] has been checked and rejected, it must be left out of the range. That is what the + 1 and - 1 do. Try leaving them out. The loop below has a step limit, called a cap, purely so the program finishes:

Step 3

function spinning(sorted, target, cap = 40) {
  let low = 0;
  let high = sorted.length - 1;
  let steps = 0;
  while (low <= high && steps < cap) {
    steps++;
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return { index: mid, steps };
    if (sorted[mid] < target) low = mid;
    else high = mid;
  }
  return { index: -1, steps };
}
console.log(spinning([1, 3, 5, 7], 4)); // { index: -1, steps: 40 }
console.log(spinning([1, 3, 5, 7], 5)); // { index: 2, steps: 2 }

Hunting for 4, the range shrinks to low 1 and high 2. mid is then 1 every time, 3 is less than 4, and low is set to 1 again. Nothing changes, so without the cap the loop never stops.

The second line is why this bug survives: when the value is in the array, the broken version often finds it and looks fine.

Step 4: count steps and remember where it would go

The full version counts its steps and returns an object. When the value is missing, it also reports insertAt: the index where the value would go to keep the array sorted. When the loop ends, low is exactly that index, so we get it for free.

Step 4

function search(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let steps = 0;
  while (low <= high) {
    steps++;
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return { index: mid, steps, insertAt: mid };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, steps, insertAt: low };
}
const ids = Array.from({ length: 1000 }, (_, i) => (i + 1) * 3); // 3, 6, 9 ... 3000
console.log(search(ids, 3000)); // { index: 999, steps: 10, insertAt: 999 }
console.log(search(ids, 3001).insertAt); // 1000: after the last one
console.log(search(ids, 4).insertAt);    // 1: between 3 and 6
console.log(search([], 5));     // { index: -1, steps: 0, insertAt: 0 }

Array.from({ length: 1000 }, ...) builds a thousand items, calling the function with each index i. The last of the thousand is found in ten steps. An empty array never enters the loop, so it takes no steps and says "insert at 0".

Step 5: what an unsorted array does

Step 5

function search(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(search([5, 1, 9, 3], 3)); // -1
console.log([5, 1, 9, 3].indexOf(3)); // 3: it is right there

The first middle is 1, which is less than 3, so the search throws away the left half and looks only at 9 and 3. In that half, 9 is too big, so it moves left again and runs out of room. Every decision assumed an order that wasn't there. If your data isn't sorted, sort it first, or use indexOf.

The full solution

The answer panel has search with its step count and insertAt, the capped spinning version, and a thousand sorted ids to search. The checks cover the ten-step finds, missing values, the empty and one-item arrays, the endless loop and the unsorted array. Press Run to see the output.

The answer

function search(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let steps = 0;
  while (low <= high) {
    steps++;
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return { index: mid, steps, insertAt: mid };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, steps, insertAt: low };      // low is where it would belong
}

// The same loop with mid instead of mid + 1. The cap is the only reason this returns.
function spinning(sorted, target, cap = 40) {
  let low = 0;
  let high = sorted.length - 1;
  let steps = 0;
  while (low <= high && steps < cap) {
    steps++;
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return { index: mid, steps };
    if (sorted[mid] < target) low = mid;
    else high = mid;
  }
  return { index: -1, steps };
}

const ids = Array.from({ length: 1000 }, (_, i) => (i + 1) * 3);   // 3, 6, 9 ... 3000
console.log('3000 is at', search(ids, 3000).index, 'found in', search(ids, 3000).steps, 'steps');
console.log('3001 is missing; it would go at', search(ids, 3001).insertAt);
console.log('the mid-instead-of-mid+1 version, hunting 4:', JSON.stringify(spinning([1, 3, 5, 7], 4)));

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('the first and last of a thousand are found in ten steps or fewer', [search(ids, 3).index, search(ids, 3000).index, search(ids, 3000).steps], [0, 999, 10]);
test('a missing value reports where it would be inserted', [search(ids, 3001).index, search(ids, 3001).insertAt, search(ids, 4).insertAt], [-1, 1000, 1]);
test('a linear scan would have compared a thousand times for the last one', [ids.indexOf(3000), ids.length], [999, 1000]);
test('ten steps because two to the tenth is past a thousand', [2 ** 10 > 1000, search(ids, 1500).steps <= 10], [true, true]);
test('an empty array takes no steps at all', search([], 5), { index: -1, steps: 0, insertAt: 0 });
test('one element, hit and miss', [search([7], 7).index, search([7], 8).index, search([7], 8).insertAt], [0, -1, 1]);
test('narrowing to mid instead of mid + 1 spins until the cap saves it', spinning([1, 3, 5, 7], 4), { index: -1, steps: 40 });
test('and it looks fine whenever the value happens to be there', spinning([1, 3, 5, 7], 5), { index: 2, steps: 2 });
test('on an unsorted array it misses a value that is present', [search([5, 1, 9, 3], 3).index, [5, 1, 9, 3].indexOf(3)], [-1, 3]);

low = mid + 1 is the whole exercise. The + 1 is what guarantees the range shrinks: once the middle has been compared and rejected it must be excluded, or a range of two elements can produce the same mid for ever. The seventh assertion is that infinite loop, held down by a step cap so this page still finishes — and the eighth shows why the bug survives review, because the same broken function returns correct answers whenever the target happens to be at a midpoint.

Returning low on failure is worth the extra line. When the loop ends, low is the index where the value would keep the array sorted, so the same function powers "insert in order" and "find the nearest" without a second pass. That is what Array.prototype.findIndex cannot give you cheaply.

The last assertion states the precondition that makes any of this legal. Binary search on unsorted data is not slow, it is wrong: it reports -1 for a value sitting in the array, because every comparison it makes assumes an order that is not there. The speed is real — ten comparisons against a thousand — but it is bought entirely with that assumption, and the cost of sorting has to be counted against however many searches you plan to run.

Common mistakes

  • Writing low = mid instead of low = mid + 1. The range stops shrinking and the loop can run for ever.
  • Using low < high as the loop condition. The last remaining item is never checked, so search([7], 7) would miss.
  • Searching an array that isn't sorted. Binary search gives wrong answers, not slow ones.

Try it yourself

  1. Build a sorted array of a million numbers and search for the last one. Check that it takes no more than 20 steps.
  2. Write insertSorted(sorted, value) that uses insertAt and splice to add a value in the right place.
  3. In [1, 2, 2, 2, 3], change search so it finds the first 2 (index 1). Hint: when you find a match, remember it and keep looking to the left.

Keep practising

Newsletter

New writing, when it lands.

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