TExcelTAD
Home › Foundations of Algorithm Analysis › Order of Growth

Order of Growth

The exact cost of insertion sort came out as an2+bn+can^2 + bn + c, with constants that depend on the machine and that nobody really knows. The previous lesson also showed that for large nn the term an2an^2 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 n2n^2, written Θ(n2)\Theta(n^2). The Asymptotic Notation section defines Θ\Theta precisely; here the goal is to see why the abstraction is the right one.

Two simplifications

From an exact formula such as T(n)=6n2+9n−12T(n) = 6n^2 + 9n - 12:

  1. Drop the lower-order terms. For large nn, 9n−129n - 12 is negligible next to 6n26n^2: their ratio tends to 0.
  2. Drop the leading coefficient. The 6 depends on the machine, the compiler and how you count; the n2n^2 does not. A machine twice as fast changes 6 into 3 and leaves the shape alone.

What remains, n2n^2, 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 T(n)≈ankT(n) \approx a n^k, then

T(2n)T(n)≈a(2n)kank=2k,\frac{T(2n)}{T(n)} \approx \frac{a (2n)^k}{a n^k} = 2^k,

so doubling nn 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 aa cancels, which is exactly why it can be ignored. The program measures this ratio with step counters for four small algorithms.

python · try it yourself
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 n(n−1)/2n(n-1)/2. For the logarithmic count, doubling adds exactly 1 step, so the ratio (lg⁡n+1)/lg⁡n(\lg n + 1)/\lg n 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 3n23n^2 steps and the other 40nlg⁡n40 n \lg n steps. For small nn the quadratic one is cheaper; from some point on it never is again. The program finds the crossover.

python · try it yourself
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 101010^{10} steps per second and machine B only 10810^8, a hundred times slower. A runs a program that takes 2n22n^2 steps, B runs one that takes 60nlg⁡n60 n \lg n. For ten million items:

python · try it yourself
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 n/lg⁡nn / \lg n. Algorithms are a technology in their own right, just as hardware is.

What "the order of growth is n2n^2" says and does not say

It says: for all large enough nn, the running time lies between two positive constant multiples of n2n^2. It does not say:

  • that the running time equals n2n^2, or n2n^2 seconds;
  • which of two Θ(n2)\Theta(n^2) 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 Θ(nlg⁡n)\Theta(n \lg n), read it as: "if I make the input 1,000 times larger, the work grows by about 1000⋅lg⁡1000nlg⁡n1000 \cdot \frac{\lg 1000n}{\lg n}, a bit over 1,000 times, not a million times."

Common orders of growth

Order Name Typical source Doubling nn multiplies work by
11 constant one array access 1
lg⁡n\lg n logarithmic halving the range (binary search) adds a constant
nn linear one pass over the input 2
nlg⁡nn \lg n linearithmic divide and conquer with linear merging (merge sort) a bit more than 2
n2n^2 quadratic all pairs (insertion sort, worst case) 4
n3n^3 cubic all triples (naive matrix multiplication) 8
2n2^n exponential all subsets (brute-force search) squares it: 22n=(2n)22^{2n} = (2^n)^2

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 nn doubles. What is its likely order of growth?

  1. nn
  2. n2n^2
  3. n3n^3
  4. 2n2^n

What is the order of growth of T(n)=5n3+1000n2lg⁡n+7T(n) = 5n^3 + 1000n^2 \lg n + 7?

  1. n2lg⁡nn^2 \lg n
  2. n3n^3
  3. 5n35n^3
  4. 1000n21000n^2

Program P takes 3n23n^2 steps and program Q takes 40nlg⁡n40 n \lg n. Which statement is true?

  1. P is faster for every nn
  2. Q is faster for every nn
  3. P is faster for small nn, but from n=86n = 86 on Q is always faster
  4. They are equally fast because both are polynomial

Why can the leading coefficient be ignored when comparing orders of growth?

  1. Because it is always 1
  2. Because it depends on the machine and implementation, and cancels in ratios such as T(2n)/T(n)T(2n)/T(n)
  3. Because it is always smaller than the lower-order terms
  4. Because only exponents can be measured