Algorithm complexity: big O notation
Theory
Machine translation, not yet reviewed by a native speaker.
How do you compare two algorithms without running them? You count how the number of operations grows as the size of the data n grows. This is written with "big O".
| notation | name | example | n = 1,000,000 |
|---|---|---|---|
| O(1) | constant | accessing a[i], a hash table |
1 |
| O(log n) | logarithmic | binary search | ~20 |
| O(n) | linear | linear search, the sum of an array | 10⁶ |
| O(n log n) | "n log n" | qsort, mergesort |
~2·10⁷ |
| O(n²) | quadratic | insertion sort, two nested loops | 10¹² — hours |
| O(2ⁿ) | exponential | trying all subsets, naive fib |
you'll never see it finish |
Counting rules:
- constants are dropped: 3n + 5 → O(n). What's interesting is the growth, not the exact number;
- the fastest-growing term is taken: n² + n → O(n²);
- nested loops over
nmultiply: O(n · n) = O(n²); consecutive ones add up: O(n + n) = O(n); - halving the task at every step gives log n.
Usually people talk about the worst case. But there are average cases too: a hash table is O(1) on average, and O(n) in the worst case, when all the keys are in one bucket.
Memory is estimated the same way: insertion sort needs O(1) extra memory, and mergesort needs O(n).
The practical takeaway. If a program is slow, first look for O(n²) where O(n log n) or O(n) is possible. For example, searching for an item in an array inside a loop can be replaced with a hash table, or with sorting plus binary search. The choice of algorithm almost always matters more than micro-optimisations like inline or register.