Linear search vs. the mighty binary search
← Back to AlgorithmsLinear search walks through a list one item at a time until it finds the target (or runs out). Simple and works on any list, sorted or not. Its speed is O(n).
Binary search only works on a sorted list, but it's lightning fast — O(log n). It checks the middle, then throws away half the list every step.
It's exactly how you find a word in a dictionary: open the middle, decide "earlier" or "later", and repeat on the half that remains.
Searching a sorted list of 1,000,000 items:
| Method | Worst-case steps | Big-O |
|---|---|---|
| Linear search | 1,000,000 | O(n) |
| Binary search | about 20 | O(log n) |
Binary search needs the list to be sorted first. If you only search once, sorting may not be worth it. If you search many times, sort once and enjoy fast lookups forever.
-1 when not.(low + high) // 2.