AlgoScope

Binary Search vs Linear Search

SearchingAlgorithmbeginner

Binary Search and Linear Search are both searching. Play them side by side below, then see exactly where they diverge.

Either player can stop before each decision and ask what happens next: turn on Predict mode in its top bar.

Binary Search

Full topic

Compare with the middle of a sorted array and half of it stops mattering.

Middle of the range from index 0 to 9 is index 4, value 16.active 0-9205182123164235386567728919lowmidhigh
The middle of indices 0 to 9 is index 4, which holds 16.

MIDDLE -> COMPARE -> DISCARD HALF -> REPEAT. Discarded cells recede, the active range contracts.

Linear Search

Full topic

Check every slot in order. On average half the array, in the worst case all of it.

Searching an unsorted array of 6 values for 2, one slot at a time.501142238435
Find 2. Nothing is sorted, so the only option is to check every slot in turn.

One pointer, one comparison per cell. No assumption about order.

How they differ

Linear search asks nothing of the array and checks each slot in order, so it is O(n) on average and in the worst case. Binary search needs the array sorted, and in exchange every comparison with the middle rules out half of what is left, so it takes O(log n). On an unsorted array only linear search applies. On a sorted array of a million values it is the difference between up to a million comparisons and about twenty.

The run shown here takes 6 steps for Binary Search and 6 steps for Linear Search (Linear search, found). That count moves with the input - use the example tabs above either player to see it change.

What each operation costs, for Binary Search and Linear Search side by side.
CostBinary SearchLinear Search
bestO(1)O(1)
averageO(log n)O(n)
worstO(log n)O(n)
spaceO(1)O(1)