Comparison Lab
Linear search vs binary search
Searching the same sorted array for the same target, how many elements does each search have to look at?
No wall-clock benchmarks: every number on this page is an operation count taken from the algorithms' traces, never a timing.
What is counted
- Elements examined
- One array element read and tested against the target. Linear search examines values[i] once per loop step; binary search examines values[mid] once per iteration (it may test that element twice, == and then <, which is still one element).
- Element-target comparisons
- One evaluation of a test between an element and the target, == or <. Linear search only tests ==; binary search tests == and then, if unequal, <. Index tests (i < n, low ≤ high) are not counted.
- Linear search: Scans from index 0 and stops at the first match.
- Binary search: Classic variant: closed range [low, high], returns any matching index.
Totals for every preset
Computed when this page was built, by running each algorithm on the preset (seed 1). The lab above replays the same traces.
| Preset | Metric | Linear search | Binary search |
|---|---|---|---|
| Target at the end | Elements examined | 32 | 6 |
| Element-target comparisons | 32 | 11 | |
| Target at the front | Elements examined | 1 | 4 |
| Element-target comparisons | 1 | 7 | |
| Target in the middle | Elements examined | 6 | 3 |
| Element-target comparisons | 6 | 5 | |
| Missing, 64 values | Elements examined | 64 | 7 |
| Element-target comparisons | 64 | 14 | |
| Duplicates | Elements examined | 2 | 1 |
| Element-target comparisons | 2 | 1 |
- Target at the end:
- 32 sorted values, target is the last one: the scan reads all 32, binary search needs 6 iterations.
- Target at the front:
- Target is the first element: the scan needs 1 element, binary search still halves 4 times on 16 values. The scan wins here.
- Target in the middle:
- Ten values, target 23 at index 5: 6 elements for the scan, 3 for binary search.
- Missing, 64 values:
- 127 is larger than every value: the scan must read all 64 to prove it is absent, binary search 7 (⌊log₂ 64⌋ + 1).
- Duplicates:
- Five 3s. The scan returns the first one (index 1); classic binary search returns the first 3 it probes (index 3). Both answers are correct for their contracts.
What to look for
Each binary-search iteration rules out about half of the remaining range, so the number of elements examined grows with log₂ n. The scan rules out one element per step, so it grows with n.
Binary search pays for that with a precondition: the array must be sorted. The scan works on any order, and wins outright when the target is among the first few elements.
Comparisons per element differ: binary search can test one element twice (== then <), so its comparison count is up to twice its elements examined.
Each side on its own, with code in four languages: Linear search, Binary search.