All lessons

Binary Search

8 min · Python examples

Cut a sorted list in half each step to find a value in logarithmic time.

Techniques · Binary Search0/5 cleared

Enemy 1 of 5

This code searches a sorted list by checking the middle item and discarding half the list each time, until it finds 23. Press Run to see whether it is found.

Why this works

Binary search only works on sorted data. Instead of checking every item, compare your target to the middle element: if it's too small, search the left half; if too large, search the right half.

Each step throws away half the remaining items, so a list of 1,000,000 items needs at most about 20 comparisons.

You
Goblin Glitch
Loading editor…
Target output: found