StringMash.com

Binary search visualizer

Watch it check the middle and throw away half the list each time.

36 characters
Updates as you type
The animation is below

Show the steps
  1. The middle of positions 1 to 10 is 31. 56 comes after it, so throw away the left half.
  2. The middle of positions 6 to 10 is 61. 56 comes before it, so throw away the right half.
  3. The middle of positions 6 to 7 is 42. 56 comes after it, so throw away the left half.
  4. The middle of positions 7 to 7 is 56. That's 56. Found at position 7, after 4 checks.

Watch it sort

  • Being compared
  • Just moved
  • In its final place
  • Not being worked on

Type a list above to see it sorted step by step.

Using the visualizer

Type a list and what to look for. Binary search only works on a sorted list, so the list is sorted first, and the position in the result is the position in that sorted list. The animation shows the part still in play; everything ruled out fades back. Show the steps lists every check.

How binary search works

Look at the middle item. If it's the one you want, you're done. If what you want comes before it, the right half can't contain it, so throw that half away; if it comes after, throw away the left half. Then look at the middle of what's left, and repeat.

It's how you'd look up a word in a paper dictionary: open it in the middle, see which side your word is on, and never look at the other side again.

Why it's so fast

Each check halves what's left, so the number of checks grows with the number of times n can be halved. In the worst case binary search needs ⌊log₂ n⌋ + 1 checks: 4 for ten items, 10 for a thousand, and 20 for a million. Linear search could need a million.

John Mauchly described binary search in the Moore School Lectures of 1946.

Questions

Why does the list need to be sorted?

Throwing half away only works if everything on one side of the middle is smaller and everything on the other side bigger. In an unsorted list, the item could be anywhere.

What if the item isn't there?

The part still in play shrinks to nothing, and the search says so, after at most ⌊log₂ n⌋ + 1 checks.

Why does the animation only go up to 3 steps a second?

Each step recolours a bar or two, and three changes a second is the limit the web's accessibility guidelines set for anything that flashes. Step forward goes as fast as you can click.