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.






