Order of Growth
The exact cost of insertion sort came out as , with constants that depend on the machine and that nobody really knows. The previous lesson also showed that for large the term accounts for almost all of it. This lesson makes the next abstraction: keep only the order of growth, the leading term without its coefficient. Insertion sort's worst case grows like , written . The Asymptotic Notation section defines precisely; here the goal is to see why the abstraction is the right one.
Two simplifications
From an exact formula such as :
- Drop the lower-order terms. For large , is negligible next to : their ratio tends to 0.
- Drop the leading coefficient. The 6 depends on the machine, the compiler and how you count; the does not. A machine twice as fast changes 6 into 3 and leaves the shape alone.
What remains, , is the order of growth. Two algorithms with different orders of growth will eventually swap places in any comparison, whatever their constants; two with the same order differ only by a constant factor.
The doubling test
The order of growth predicts what happens when the input gets bigger. If , then
so doubling multiplies the work by about 2 for linear algorithms, 4 for quadratic ones and 8 for cubic ones, while a logarithmic algorithm only adds a constant. The constant cancels, which is exactly why it can be ignored. The program measures this ratio with step counters for four small algorithms.
def linear_steps(n): # one pass over the input
return sum(1 for _ in range(n))
def quadratic_steps(n): # insertion sort on reversed input: shifts
return n * (n - 1) // 2
def cubic_steps(n): # three nested loops over 0..n-1
count = 0
for i in range(n):
for j in range(n):
for k in range(n):
count += 1
return count
def log_steps(n): # halving until 1
count = 0
while n > 1:
n //= 2
count += 1
return count
algos = [("log", log_steps), ("linear", linear_steps),
("quadratic", quadratic_steps), ("cubic", cubic_steps)]
for name, f in algos:
ratios = [f(2 * n) / f(n) for n in [16, 32, 64]]
print(f"{name:>9}: T(2n)/T(n) = " + ", ".join(f"{r:.3f}" for r in ratios)) log: T(2n)/T(n) = 1.250, 1.200, 1.167
linear: T(2n)/T(n) = 2.000, 2.000, 2.000
quadratic: T(2n)/T(n) = 4.133, 4.065, 4.032
cubic: T(2n)/T(n) = 8.000, 8.000, 8.000
The quadratic ratios approach 4 from above because of the lower-order term in . For the logarithmic count, doubling adds exactly 1 step, so the ratio creeps towards 1. Running a doubling experiment like this on step counts of real code is a quick way to discover its order of growth, and the Mini Project builds a tool around it.
Growth beats constants
Constants still matter for a fixed input; order of growth decides what happens as inputs grow. Consider two hypothetical sorting programs, one making steps and the other steps. For small the quadratic one is cheaper; from some point on it never is again. The program finds the crossover.
import math
quad = lambda n: 3 * n * n
nlog = lambda n: 40 * n * math.log2(n)
n = 2
while quad(n) <= nlog(n):
n += 1
print("3n^2 first exceeds 40 n lg n at n =", n)
for m in [10, 50, n, 1000, 10**6]:
print(f"n = {m:>9,}: 3n^2 = {quad(m):>16,.0f} 40 n lg n = {nlog(m):>14,.0f} ratio {quad(m) / nlog(m):>9.2f}")3n^2 first exceeds 40 n lg n at n = 86
n = 10: 3n^2 = 300 40 n lg n = 1,329 ratio 0.23
n = 50: 3n^2 = 7,500 40 n lg n = 11,288 ratio 0.66
n = 86: 3n^2 = 22,188 40 n lg n = 22,106 ratio 1.00
n = 1,000: 3n^2 = 3,000,000 40 n lg n = 398,631 ratio 7.53
n = 1,000,000: 3n^2 = 3,000,000,000,000 40 n lg n = 797,262,743 ratio 3762.87
A coefficient 13 times smaller only bought the quadratic program the inputs below 86. At a million items it does nearly 4,000 times as much work. Practical sorting libraries use exactly this insight in reverse: merge sort and quicksort implementations hand short subarrays (a few dozen elements) to insertion sort, whose small constant wins there.
Faster hardware does not change the order
Suppose machine A executes steps per second and machine B only , a hundred times slower. A runs a program that takes steps, B runs one that takes . For ten million items:
import math
n = 10**7
a_steps = 2 * n * n
b_steps = 60 * n * math.log2(n)
a_seconds = a_steps / 1e10
b_seconds = b_steps / 1e8
print(f"machine A (fast, 2n^2): {a_steps:.3e} steps, {a_seconds:,.0f} s = {a_seconds / 3600:.1f} hours")
print(f"machine B (slow, 60 n lg n): {b_steps:.3e} steps, {b_seconds:,.0f} s = {b_seconds / 60:.1f} minutes")machine A (fast, 2n^2): 2.000e+14 steps, 20,000 s = 5.6 hours
machine B (slow, 60 n lg n): 1.395e+10 steps, 140 s = 2.3 minutes
The slow machine with the better algorithm finishes in under three minutes; the fast machine needs most of a working day, about 140 times longer. No realistic hardware speed-up closes a gap that grows like . Algorithms are a technology in their own right, just as hardware is.
What "the order of growth is " says and does not say
It says: for all large enough , the running time lies between two positive constant multiples of . It does not say:
- that the running time equals , or seconds;
- which of two algorithms is faster (that depends on constants, and needs measurement or exact counts);
- anything about small inputs, where lower-order terms and constants dominate;
- anything about memory, which is analysed separately.
Order of growth is a statement about scaling. When an analysis says an algorithm is , read it as: "if I make the input 1,000 times larger, the work grows by about , a bit over 1,000 times, not a million times."
Common orders of growth
| Order | Name | Typical source | Doubling multiplies work by |
|---|---|---|---|
| constant | one array access | 1 | |
| logarithmic | halving the range (binary search) | adds a constant | |
| linear | one pass over the input | 2 | |
| linearithmic | divide and conquer with linear merging (merge sort) | a bit more than 2 | |
| quadratic | all pairs (insertion sort, worst case) | 4 | |
| cubic | all triples (naive matrix multiplication) | 8 | |
| exponential | all subsets (brute-force search) | squares it: |
The Comparing Growth Rates lesson puts these side by side in an interactive chart.
Test yourself
An algorithm's step count roughly multiplies by 8 every time doubles. What is its likely order of growth?
What is the order of growth of ?
Program P takes steps and program Q takes . Which statement is true?
- P is faster for every
- Q is faster for every
- P is faster for small , but from on Q is always faster
- They are equally fast because both are polynomial
Why can the leading coefficient be ignored when comparing orders of growth?
- Because it is always 1
- Because it depends on the machine and implementation, and cancels in ratios such as
- Because it is always smaller than the lower-order terms
- Because only exponents can be measured