এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ
13Asymptotic Analysis and Recurrences
Two programs sort thirty million records, and both are correct. On a machine that performs a billion elementary operations a second, the first finishes in under a second and the second runs for more than ten days. Neither the language nor the machine makes the difference: the first does about operations and the second about . This chapter makes such statements precise: what is counted, how costs are compared when grows, how the cost of an algorithm differs between its best, worst and average inputs, and how to solve the recurrences that the cost of a recursive algorithm obeys.
You already know
For sequences and of positive reals, means that becomes negligible beside . For and : , and . The sum , and for . Insertion sort inserts each element into the sorted part before it, shifting the larger elements one place to the right.
13.1 What the model counts
Definition 13.1 (Model of computation, elementary operation)
The RAM model is a model of computation: an idealised machine with a memory of numbered cells, each holding a machine word, in which each elementary operation costs one unit of time — an arithmetic operation or a comparison on words, reading or writing a cell, a jump. Words have bits for inputs of size , enough to index the input.
Definition 13.2 (Input size, cost function)
The input size is a natural number measuring an input: the length of a list, the number of vertices and edges of a graph, the number of bits of an integer. The cost of an algorithm on an input is the number of elementary operations it performs; a cost function gives a cost for each size.
Counting every operation is tedious and depends on details of the translation to machine code, so in practice one counts a single operation that dominates: the comparisons of a sort, the multiplications of an arithmetic algorithm. The other operations are at most a constant multiple of it. A counter added to the program makes the count observable.
def insertion_sort(a):
"""Sorts a in place and returns the number of comparisons between elements."""
comparisons = 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0:
comparisons += 1
if a[j] <= key:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return comparisons
$ python count_ops.py
n sorted reversed random n(n-1)/4
8 7 28 19 14
16 15 120 48 60
32 31 496 280 248
64 63 2016 1104 1008
128 127 8128 3883 4064
256 255 32640 16308 16320
512 511 130816 65014 65408
On a sorted list, each insertion stops at its first comparison: comparisons. On a reversed list, the -th insertion goes to the front, with comparisons: . A shuffled list lands near , which Section 13.3 explains. Constants are dropped for two reasons: they depend on the machine and the compiler, which the model abstracts away, and they matter less than the growth as soon as is large. The model also hides the memory hierarchy: on a real machine, an access to a cell far from the last ones costs much more than a comparison, which the second year studies.
13.2 , and
Definition 13.3 (Big O, big Omega, big Theta)
Let . Then if there are a constant and a rank with for all ; if , that is from some rank on for some ; and if both hold.
One often writes ; the equality sign is then read as “belongs to”. The constant and the rank are chosen once, before : Exercise 13.5 shows what goes wrong otherwise. If has a limit , then gives , and gives .
Proposition 13.4 (Rules for O)
For cost functions and : and ; if moreover , then . The same rules hold for and .
Proof. With from on and from on: from on, and . For transitivity, from some rank on gives . ∎
The sum rule says that a sequence of steps costs as much as its most expensive step, and the product rule that a loop costs its number of iterations times the cost of one iteration, when that cost does not depend on the iteration.
Proposition 13.5 (The scale of growth)
For and , as : , and , and none of these is a . Moreover , so the base of a logarithm does not matter inside .
Proof. The three limits recalled at the start of the chapter are 0, which gives each and excludes each . And is a constant multiple. ∎
$ python growth.py
n log2 n n log2 n n^2 n^3 2^n
2 1 2 4 8 4
4 2 8 16 64 16
8 3 24 64 512 256
16 4 64 256 4096 65536
32 5 160 1024 32768 4294967296
64 6 384 4096 262144 18446744073709551616
n log2 n: 7.45e+08 operations, 0.7 s = 0.00 days
n^2: 9.00e+14 operations, 900,000.0 s = 10.42 days
is only an upper bound. “Merge sort is in ” is true and useless; “insertion sort is in ” holds for every input, including the sorted ones that it finishes in comparisons. A lower bound needs , and a precise statement needs , with the input class it is about.
13.3 Worst, best and average case
Definition 13.6 (Worst-case, best-case and average-case cost)
For an algorithm whose cost on an input is , and the finite set of inputs of size considered, the worst-case cost is , the best-case cost is , and the average-case cost is .
For a comparison sort on distinct keys, only the order of the keys matters, so can be taken as the orders of . For insertion sort, the best case is and the worst ; the average needs a count.
Proposition 13.7 (Average cost of insertion sort)
Over the orders of distinct keys, insertion sort makes on average exactly comparisons, where . This is in .
Proof. An inversion of an order is a pair of positions whose keys are in decreasing order. In insertion sort, each comparison either shifts an element, which removes exactly one inversion, or stops the inner loop. The inner loop stops on a comparison unless the key reaches the front, which happens exactly when the key is smaller than every key before it, a left-to-right minimum. So an order with inversions and left-to-right minima (the first key counts) costs .
Average of : exchanging the keys at two positions is a one-to-one correspondence between the orders where the pair is inverted and those where it is not, so each of the pairs is inverted in exactly half of the orders: the total of is , and the average . Average of : position (from 0) holds a left-to-right minimum when it holds the smallest of the first keys; grouping the orders by the set of those keys and the arrangement of the rest, that smallest key is at each of the positions equally often, so in exactly of the orders. Summing over , the average of is , and the average cost is . As , it lies between and . ∎
$ python inversions.py
n orders average n(n-1)/4 + n - H_n
1 1 0 0
2 2 1 1
3 6 8/3 8/3
4 24 59/12 59/12
5 120 463/60 463/60
6 720 221/20 221/20
7 5040 2087/140 2087/140
8 40320 5399/280 5399/280
Definition 13.8 (Space cost)
The space cost of an algorithm is the number of memory cells it uses beyond its input, at its peak, as a function of the input size; the stack frames of recursive calls count.
Insertion sort uses cells beyond the list: it sorts in place. A merge sort that copies its halves uses cells, and the recursion of a binary search uses frames where the loop of Chapter 12 uses .
13.4 Sums
Nested loops give sums. A double loop over performs iterations; a triple loop over performs (Exercise 13.7). A loop that doubles from 1 until runs times. Three tools bound the sums that have no closed form.
Method 13.9 (Bounding a sum)
- Bound each term by the largest: , an upper bound.
- Split: for increasing, the terms from on are at least , so , a lower bound of the same order as the upper one when .
- Compare with an integral: for decreasing on , .
Proposition 13.10 (Harmonic numbers and )
, so ; and .
Proof. The integral of from 1 to is , and from 1 to it is ; the third rule gives the first claim. For the second, by the first rule, and by the second, which is at least for . ∎
The harmonic number thus contributes only to the average of insertion sort, and will be the number of comparisons that any comparison sort needs in the worst case (Chapter 19).
13.5 Recurrences
Definition 13.11 (Recurrence relation, recursion tree)
A recurrence relation defines a cost function by its values on small sizes and an equation expressing in terms of values on smaller sizes. The recursion tree of such an equation has a node for each call, labelled with the cost spent in that call outside its recursive calls; its children are the calls it makes. is the sum of all the labels, which one often computes level by level.
A recursive algorithm gives a recurrence directly: binary search halves its interval with one comparison, ; merge sort sorts two halves and merges them with at most comparisons, . Three methods solve them. Unrolling substitutes the equation into itself: for a power of 2. The recursion tree sums level by level. And one can guess and prove by induction, the guess coming from either method or from computed values.
$ python recurrences.py
n T1 T2 T3 T4 closed forms
1 0 0 1 1 all equal
4 2 8 19 28 all equal
16 4 64 211 496 all equal
64 6 384 2059 8128 all equal
256 8 2048 19171 130816 all equal
1024 10 10240 175099 2096128 all equal
The forms of and come from the proof below; checking them by induction is short. For : , and .
Theorem 13.12 (Master theorem)
Let , an integer, , and defined on the powers of by and . Then
Proof. Let . Unrolling, level of the recursion tree has nodes of size , each costing , and the leaves cost each:
Note that . If , then and ; and , so ; hence . If , then and , between 0 and ; so . The case is Exercise 13.10. ∎
Remark 13.13
Algorithms split into and parts, and their combining costs are plus lower terms. The conclusions still hold for such recurrences when is increasing: lies between its values at the powers of around , which are within a constant factor of each other. Exercise 13.11 treats merge sort’s recurrence with floors and ceilings exactly.
def master(a, b, k):
"""For a >= 1, b >= 2, k >= 0: the case, the order of T, and a function g
with T in Theta(g)."""
if a < b**k:
return "root", f"n^{k}", lambda n: n**k
if a == b**k:
return "even", f"n^{k} log n", lambda n: n**k * log(n, b)
e = log(a, b)
return "leaves", f"n^{e:.3f}", lambda n: n**e
$ python master.py
a b k case Theta T/g at 2^10, 2^20
binary search 1 2 0 even n^0 log n 1.100 1.050
merge sort 2 2 1 even n^1 log n 1.100 1.050
Karatsuba 3 2 1 leaves n^1.585 2.965 2.999
eight products 8 2 2 leaves n^3.000 1.999 2.000
Strassen 7 2 2 leaves n^2.807 2.328 2.333
square at the root 2 2 2 root n^2 1.999 2.000
Karatsuba’s multiplication of -digit numbers replaces four half-size products by three, which moves the cost from to ; Strassen’s product of matrices replaces eight half-size products by seven, from to . Both are leaf-dominated: the count of subproblems matters more than the cost of combining them. The ratio for merge sort, , shows how slowly the lower term fades.
13.6 Counts and times
A count predicts a time if each counted operation costs about the same. The doubling test checks the order of a cost from measurements alone: double and look at the ratio of the costs. For a cost plus lower terms the ratio tends to 4, for to 2, and for it equals , slightly above 2 and tending to 2. The weekend problem proves these, and shows that a class alone is not enough: a cost in can have a ratio that never settles.
rng = random.Random(2026)
previous = None
print(f"{'n':>5} {'maximum':>8} {'merge sort':>10} {'insertion':>10} ratios")
for n in [500, 1000, 2000, 4000, 8000]:
a = rng.sample(range(10 * n), n)
c_max, c_merge = [0], [0]
maximum(a, c_max)
merge_sort(a, c_merge)
counts = (c_max[0], c_merge[0], insertion_sort(list(a)))
ratios = "" if previous is None else " ".join(
f"{c / p:5.2f}" for c, p in zip(counts, previous))
print(f"{n:5d} {counts[0]:8d} {counts[1]:10d} {counts[2]:10d} {ratios}".rstrip())
previous = counts
$ python doubling.py
n maximum merge sort insertion ratios
500 499 3847 66704
1000 999 8727 256421 2.00 2.27 3.84
2000 1999 19374 987402 2.00 2.22 3.85
4000 3999 42840 3988459 2.00 2.21 4.04
8000 7999 93609 16180928 2.00 2.19 4.06
$ python timing.py
n max (ms) merge (ms) ins. (ms) ratios
500 0.028 0.375 2.3
1000 0.057 0.818 10.1 2.02 2.18 4.39
2000 0.117 1.846 39.9 2.07 2.26 3.94
4000 0.260 4.627 165.4 2.23 2.51 4.15
8000 0.480 8.746 635.7 1.85 1.89 3.84
The time ratios scatter around the count ratios: a measurement on a real machine includes caches, the interpreter and the other programs running at the same time. The counts are exact and repeatable; the times say what the counts cost on one machine.
In practice
To estimate an unknown cost, run the program for sizes until the time is a second or more, and look at the ratios. A ratio near 2 suggests linear time; near 4 quadratic; near 8 cubic. A ratio that keeps growing suggests exponential time, and the end of the experiment.
13.7 Exercises
Exercise 13.1 ★
Predict what the program prints, and give the two counts as functions of the bounds 10 and 1000.
count = 0
for i in range(10):
for _j in range(i, 10):
count += 1
print(count)
k, steps = 1, 0
while k < 1000:
k, steps = 2 * k, steps + 1
print(k, steps)
Solution
Solution of Exercise 13.1.
55
1024 10
For each the inner loop runs times: , in general . The second loop doubles until it reaches 1000: after 10 steps, in general steps for a bound that is not a power of 2.
Exercise 13.2 ★
Order by growth, from slowest to fastest: , , , , . Justify each step with Proposition 13.5.
Solution
Solution of Exercise 13.2.
. First, . Then trivially. Next . Last, since .
Exercise 13.3 ★
With and , compute , guess a closed form, and prove it.
Solution
Solution of Exercise 13.3.
, , , . Guess : true for , and . It is , the leaf case of the master theorem ().
Exercise 13.4 ★
Which case of the master theorem applies, and what is the order of ? (a) . (b) . (c) . (d) .
Solution
Solution of Exercise 13.4.
(a) : leaves, . (b) : even, . (c) : root, . (d) and : even, .
Exercise 13.5 ★★
Find the error. “We prove by induction on . For , with . If , then with . So .”
Solution
Solution of Exercise 13.5.
The statement asks for one constant valid for all large . The “induction” proves with a constant that grows at each step: , , so . What it proves is , which is true and says nothing. An induction for a statement must keep the same constant in the hypothesis and the conclusion, and here it cannot: is unbounded.
Exercise 13.6 ★★
A student reasons: “the inner loop runs at most times, so the function costs ”. What is right and what is wrong? Find the true order, and prove it.
def doublings(n):
count = 0
for i in range(1, n + 1):
j = i
while j < n: # "at most log2 n times, so n log2 n in all"
j *= 2
count += 1
return count
n= 1024 count= 2036 count/n=1.988 count/(n log2 n)=0.199
n= 8192 count= 16369 count/n=1.998 count/(n log2 n)=0.154
n= 65536 count= 131054 count/n=2.000 count/(n log2 n)=0.125
Solution
Solution of Exercise 13.6.
The bound is right, but it is not a : the inner loop runs times only for small . For a given it runs times, and at least times exactly when , for fewer than values of . Summing over , the count is below ; and it is at least , since each runs once. So the cost is , and the output shows approaching 2 while tends to 0.
Exercise 13.7 ★★
Write count_triples(n), which counts the iterations of three nested loops over . Find a closed form, prove it, and test it against the counter.
Solution
Solution of Exercise 13.7.
def count_triples(n):
count = 0
for i in range(n):
for j in range(i + 1, n):
for _k in range(j + 1, n):
count += 1
return count
def closed_form(n):
return n * (n - 1) * (n - 2) // 6
Each iteration corresponds to one set of three distinct indices written in increasing order, and each such set to one iteration: there are of them, in . The test compares the counter with the formula for .
Exercise 13.8 ★★
Prove that .
Solution
Solution of Exercise 13.8.
Upper bound: each term is at most , so the sum is at most . Lower bound: the terms with , at least of them, are at least , so the sum is at least for .
Exercise 13.9 ★★
Solve exactly , , and , . Why does the master theorem not apply?
Solution
Solution of Exercise 13.9.
. For , , so and ; both closed forms follow by induction, and the test checks them to . The master theorem covers subproblems of size , a constant fraction of ; here the size decreases by 1, and the recursion tree has levels instead of .
Exercise 13.10 ★★★
Prove the case of Theorem 13.12: give exactly for , and deduce .
Solution
Solution of Exercise 13.10.
With , the sum is and , so exactly. For , , so : , the base of the logarithm being irrelevant.
Exercise 13.11 ★★★
Let and for . Prove that is increasing and that ; then check that for every .
Solution
Solution of Exercise 13.11.
Increasing, by strong induction: ; for , and , all four at most , so by the hypothesis . Order: for , and , using the power-of-2 values of Output 13.4. So . Exact form: the test checks for every , and also .
Exercise 13.12 ★★★
Write identify(a, b, k), which computes for and , estimates the exponent of from the numbers, and says which case of the master theorem the numbers show, without using the comparison of with . Test it against Listing 13.2.
Solution
Solution of Exercise 13.12.
def values(a, b, k, levels):
"""T(b^0), ..., T(b^levels), with T(1) = 1."""
t = [1]
for i in range(1, levels + 1):
t.append(a * t[-1] + b ** (i * k))
return t
def identify(a, b, k, levels=40):
"""Estimates the exponent e of T from the last two values, and says which
case of the master theorem the numbers show."""
t = values(a, b, k, levels)
e = log(t[-1] / t[-2], b) # T(bn) / T(n) is about b^e
if abs(e - k) > 0.05 and e > k:
return "leaves", e
# n^k times log n: T(n) / n^k grows by about one each level
growth = t[-1] / b ** (levels * k) - t[-2] / b ** ((levels - 1) * k)
return ("even" if growth > 0.5 else "root"), e
The values follow the recurrence directly, as integers. The ratio of the last two values is about for , and about in the even case: an exponent clearly above means the leaves dominate. Otherwise the quotient distinguishes the two other cases: it grows by about one per level in the even case (it is ) and converges in the root case. The test compares the answer with Listing 13.2 on eleven recurrences.
13.8 Problem: Three ways to find a duplicate
Problem 13.1
Weekend problem — Three ways to find a duplicate
The town’s library keeps its loans in order; which books were borrowed more than once among the first loans? Three functions answer, each counting its operations: one comparison of two loans, one comparison of neighbours after sorting, or one look-up in a set.
def by_pairs(xs):
ops, found = 0, set()
for i in range(len(xs)):
for j in range(i + 1, len(xs)):
ops += 1 # one comparison
if xs[i] == xs[j]:
found.add(xs[i])
return found, ops
def by_sorting(xs):
counter = [0]
s = merge_sort(xs, counter)
found = set()
for i in range(1, len(s)):
counter[0] += 1 # one comparison of neighbours
if s[i] == s[i - 1]:
found.add(s[i])
return found, counter[0]
def by_set(xs):
ops, seen, found = 0, set(), set()
for x in xs:
ops += 1 # one look-up in seen, with its insertion
if x in seen:
found.add(x)
seen.add(x)
return found, ops
$ python duplicates.py
n dup pairs sorting set ratios
25 5 300 112 25
50 11 1225 275 50 4.08 2.46 2.00
100 29 4950 639 100 4.04 2.32 2.00
200 59 19900 1476 200 4.02 2.31 2.00
400 78 79800 3359 400 4.01 2.28 2.00
Part I — The double loop.
- Show that
by_pairsmakes exactly comparisons, whatever the data. - Deduce that it is in , in the best, the worst and the average case.
- Check the column
pairsof the table. - Compute the ratio of the counts for and , and its limit.
- Could the function stop early? Rewrite its specification so that it can (“is there a duplicate?”), and give its best and worst cases then.
- What is its space cost, beyond the input and the answer?
Part II — Sort, then scan.
- Show that after sorting, two equal values are neighbours, and that the scan finds every duplicated value.
- Merge sort makes at most comparisons, with and . Show that .
- Deduce that
by_sortingis in . - On the table, compare the counts with for .
- Show that , and compute it for and .
- Why are the measured ratios not exactly these values?
Part III — A set of seen values.
- Show that
by_setmakes exactly look-ups. - Under which assumption on the set is its cost in ? (Hash tables are studied in Chapter 16.)
- What is the space cost of each of the three methods?
- The book identifiers are numbers from 1 to 80. Give a method that uses a list of 80 booleans instead of a set, and its cost.
- For , how many times fewer operations does the set make than the double loop?
- Why does the table count only one operation per look-up, when a look-up does several elementary operations?
Part IV — The doubling ratio.
- For a cost , show that exactly.
- For with , show that the ratio tends to .
- For only, can the ratio of fail to converge? Give an example.
- Read the ratios of the table, and say which order each column suggests.
- Why do the ratios of the merge sort column approach 2 so slowly?
- State the named result of the problem, the doubling ratio test: the limits of the ratios for counts , and , proved, and the values read from the table.
Solution
Solution of Problem 13.1.
1. For each the inner loop runs times: , independent of the values.
2. Every input of size costs the same, so the three cases coincide, in .
3. , , , and .
4. ; for it is .
5. Return as soon as two equal values are found. Best case: the first two loans are of the same book, one comparison; worst case: no duplicate, comparisons.
6. : two indices and a counter.
7. In a sorted list the occurrences of a value form one block of consecutive positions; a value occurring at least twice has two neighbours in its block, which the scan compares.
8. By strong induction, with : since , both halves have at most elements, so .
9. At most comparisons to sort and to scan: .
10. ; the count is 3359, of which 399 for the scan: merge sort used about 2960, below the bound, because a merge stops comparing when one half is exhausted.
11. . For : ; for : . The table shows 2.46 and 2.28.
12. The counts are not exactly : the merges depend on the data, and the scan adds a linear term.
13. One look-up per element of the list: .
14. That a look-up and an insertion each cost a bounded number of elementary operations, which hash tables achieve on average.
15. The double loop ; sorting , for the copies made by merge sort; the set as many cells as there are distinct values, at most (here at most 80).
16. seen = [False] * 81; for each x, test and set seen[x]: steps of constant cost, plus 81 to create the list, time and space for a fixed range of identifiers.
17. times fewer.
18. The model counts one dominant operation; each look-up costs a bounded number of elementary operations, so the true cost is within a constant factor of the count, which ignores.
19. .
20. Dividing numerator and denominator by : .
21. Yes. when is even and when it is odd is in , but alternates between 6 and .
22. pairs: 4.08, 4.04, 4.02, 4.01, quadratic; sorting: 2.46, 2.32, 2.31, 2.28, slightly above 2 and decreasing, ; set: exactly 2.00, linear.
23. The excess decreases like a logarithm: it is still 0.2 at and 0.1 at about a million.
24. The doubling ratio test: when doubles, the ratio of the counts tends to 4 for (question 19), to 2 for , and equals for (question 11), which tends to 2 from above. On the table the double loop gives 4.08 down to 4.01, sorting 2.46 down to 2.28, and the set 2.00: , and . The test is a diagnosis, not a proof: question 21 shows a cost whose ratio never settles.