Binary Search

IntermediateAbout 12 minProgramming & algorithms

You've been doing this the whole time. Every LogicDash guess uses feedback to make the next guess smarter — binary search is the most famous version of that idea.

The Guessing Game

"I'm thinking of a number from 1 to 100. After each guess, I'll tell you if the answer is higher or lower."

You could guess 1, then 2, then 3, and so on. You'd get there eventually — but it might take 100 guesses. Almost nobody plays that way. Instead, most people start with 50. If the answer is "higher," every number from 1 to 50 is gone in one guess. Then they try 75, and so on.

Binary search: guess the middle, throw away the half that can't be right, repeat.

Your turn first

I'm thinking of a number from 1 to 100. Find it in as few guesses as you can — after each guess I'll say higher or lower.

It could be anything from 1 to 100.

    Linear search

    Check every item in order, one at a time, until you find it.

    Works on any list, even a jumbled one. Slow on long lists.

    Binary search

    Check the middle item, then keep only the half that could hold the answer.

    Much faster — but only works if the list is already sorted.

    Now watch both methods race

    Hidden number: ?

    Linear search

    Check 1, then 2, then 3…

    No guesses yet

    0Guesses
    100Still possible

    Binary search

    Always guess the middle

    No guesses yet

    0Guesses
    100Still possible

    Press “Next guess” — both searches take one guess at a time.

    Why Halving Is So Powerful

    Each binary-search guess cuts the possibilities in half. Double the size of the list, and you only need one more guess. Here's the most guesses each method could ever need (the worst case):

    Numbers to searchLinearBinary
    10104
    1001007
    1,0001,00010
    1 million1 million20
    1 billion1 billion30

    Notice the binary column: 7 guesses covers 100 numbers because 7 halvings is the same as the doubling you've seen with bits — 27 = 128, which is more than 100. Thirty guesses is enough to search a billion sorted items.

    The Catch: It Has to Be Sorted

    Binary search only works because "higher" or "lower" tells you which half to throw away. That only makes sense if the items are in order. You can't binary-search a shuffled deck of cards — the middle card tells you nothing about where the others are.

    That's why computers spend so much effort sorting data: sorting once makes every later search fast. See how sorting works on the Sorting Algorithms page.

    Where You'll Meet It

    • Looking up a word in a paper dictionary — you open near the middle, not at page one.
    • Finding a contact in your phone, or a product in a huge online store.
    • Programmers hunting for the exact change that broke their code, by testing halfway points.