About this visualization
Binary search finds a value in a sorted list by comparing the target with the middle item and discarding the half that cannot contain it. Because the range halves every step, even a million items need at most about 20 comparisons.
How it works
- Set low and high to the ends of the list; look at the middle item.
- If it equals the target, done. If the target is smaller, search the left half; otherwise the right half.
- Stop when the range is empty — the target is not present.
Worked example
Search for 56 in the sorted list [3, 7, 19, 21, 42, 56, 64, 88]. low = 0, high = 7, mid = 3 (21 < 56) → low = 4. (56) → found at index 5 after 2 comparisons. A linear search would have needed 6.
Enter these numbers in the simulator above to see every step.
Complexity and properties
| Best case | |
|---|---|
| Average case | |
| Worst case | |
| Space |
Requires sorted input. For 1,000,000 items at most about 20 comparisons.
When to use it
- Fast lookup in sorted arrays and files.
- Understanding logarithmic time complexity.
- The basis for bisection methods and many interview questions.
Frequently asked questions
What is the time complexity of binary search?
in the average and worst cases, in the best case, with space for the iterative version.
Does binary search require a sorted list?
Yes. Without sorted order the discarded half might contain the target.
How many comparisons does binary search need for 1,000,000 items?
At most comparisons.