Linear Search vs Binary Search
Across our 4 test inputs, Binary Search needed 17 comparisons in total versus 42 for Linear Search. On average Linear Search runs in O(n) time and Binary Search in O(log n). Binary Search only works on sorted data.
Head-to-head on identical inputs (comparisons)
| Input | Linear Search | Binary Search |
|---|---|---|
| Target is first | 1 | 4 |
| Target in the middle | 9 | 4 |
| Target is last | 16 | 5 |
| Target absent | 16 | 4 |
Complexity
| Linear Search | Binary Search | |
|---|---|---|
| Average time | O(n) | O(log n) |
| Worst time | O(n) | O(log n) |
| Space | O(1) | O(1) |
| Stable | Yes | Yes |
When to use Linear Search
Unsorted arrays, small datasets, or when you need to find all occurrences.
When to use Binary Search
Sorted arrays when O(log n) search time is needed. Foundation for many advanced algorithms.