Data Structures & Algorithms / Module 4: Searching and sorting

Topic 4.1

Linear search vs binary search

On sorted data, every guess throws away half the possibilities: a million items take about 20 steps.

10 min · beginner

Watch: every step throws away half the remaining blocks. Compare binary search's step count with searching one by one.

0123456789101112131415381215212429333841475256637077

Find 41. Starting range: index 0 to 15.

The middle element being comparedElements still in the search rangeElements already thrown away16 sorted values on a rail, each block as tall as its value. Every step compares the middle block with the target, then half of what is left is thrown away and dims. 16 elements need at most 5 comparisons; 1 million elements need 20.

Like a number-guessing game

A friend thinks of a number from 1 to 100 and will only answer "higher" or "lower". Guessing 1, 2, 3 and so on can take 100 guesses. A smart player guesses 50 first. If the answer is "higher", 1 to 50 are gone in one go. The next guess is 75, then 63, and so on. Seven guesses at most.

That is binary search. In the figure the blocks are sorted from small to large. Press Step and watch: the middle block is compared with the target, then the half that can't contain it dims.

How fast is it?

Every step throws away half. So twice as much data needs just one more step:

ItemsOne by one (worst case)Binary search (worst case)
16165
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

In Big-O terms, checking one by one is O(n) and binary search is O(log n).

The catch: the data must be sorted

Throwing half away is only allowed if we are sure everything on the left is smaller and everything on the right is larger. On shuffled data, binary search still gives an answer, but it can be wrong, and no error warns you. Sorting first takes time too, so it only pays off when you will search many times.

Code, for programmersBinary search, explained line by line
function binarySearch(list, target) {
  let lo = 0;                       // left edge of what is still possible
  let hi = list.length - 1;         // right edge
  while (lo <= hi) {                // stop when nothing is left
    const mid = lo + ((hi - lo) >> 1);   // the middle
    if (list[mid] === target) return mid;
    if (list[mid] < target) lo = mid + 1;   // too small: drop the left half
    else hi = mid - 1;                      // too big: drop the right half
  }
  return -1;                        // nothing left: it isn't there
}

Where the idea is used

  • Databases find one row among millions in a few steps, using a search much like this one (an index).
  • Finding when a bug appeared: git bisect tests the version in the middle of the history, then throws half away.
  • Finding a limit, such as the largest image size that still fits, by guessing in the middle and narrowing down.

Quiz

  1. What must be true for binary search to give the right answer?

  2. At most how many steps to search 1,000 sorted items?

  3. The middle value is smaller than what you are looking for. What next?

  4. You have 1 million shuffled items and will search them only once. Best choice?

0 of 4 answered.