কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 nlog⁡2nn \log_2 n operations and the second about n2n^2. This chapter makes such statements precise: what is counted, how costs are compared when nn 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 uu and vv of positive reals, lim⁡un/vn=0\lim u_n/v_n = 0 means that uu becomes negligible beside vv. For a>0a > 0 and b>1b > 1: (log⁡n)/na→0(\log n)/n^a \to 0, na/bn→0n^a/b^n \to 0 and bn/n!→0b^n/n! \to 0. The sum 1+2+⋯+n=n(n+1)/21 + 2 + \dots + n = n(n + 1)/2, and 1+q+⋯+qm−1=(qm−1)/(q−1)1 + q + \dots + q^{m - 1} = (q^m - 1)/(q - 1) for q≠1q \neq 1. 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 Θ(log⁡n)\Theta(\log n) bits for inputs of size nn, enough to index the input.

Definition 13.2 (Input size, cost function)

The input size nn 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
Listing 13.1. Insertion sort, counting its comparisons code/bachelor-1/13-asymptotic-analysis/listings/count_ops.py
$ 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
Output 13.1. Comparisons on a sorted, a reversed and a shuffled list.

On a sorted list, each insertion stops at its first comparison: n−1n - 1 comparisons. On a reversed list, the ii-th insertion goes to the front, with ii comparisons: 1+2+⋯+(n−1)=n(n−1)/21 + 2 + \dots + (n - 1) = n(n - 1)/2. A shuffled list lands near n(n−1)/4n(n - 1)/4, 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 nn 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 OO, Ω\Omega and Θ\Theta

Definition 13.3 (Big O, big Omega, big Theta)

Let f,g:N→R+f, g : \mathbb{N} \to \mathbb{R}_+. Then f∈O(g)f \in O(g) if there are a constant c>0c > 0 and a rank n0n_0 with f(n)≤c g(n)f(n) \leq c\,g(n) for all n≥n0n \geq n_0; f∈Ω(g)f \in \Omega(g) if g∈O(f)g \in O(f), that is f(n)≥c g(n)f(n) \geq c\,g(n) from some rank on for some c>0c > 0; and f∈Θ(g)f \in \Theta(g) if both hold.

One often writes f=O(g)f = O(g); the equality sign is then read as “belongs to”. The constant cc and the rank n0n_0 are chosen once, before nn: Exercise 13.5 shows what goes wrong otherwise. If f(n)/g(n)f(n)/g(n) has a limit ℓ\ell, then ℓ<∞\ell < \infty gives f∈O(g)f \in O(g), and 0<ℓ<∞0 < \ell < \infty gives f∈Θ(g)f \in \Theta(g).

Proposition 13.4 (Rules for O)

For cost functions f1∈O(g1)f_1 \in O(g_1) and f2∈O(g2)f_2 \in O(g_2): f1+f2∈O(max⁡(g1,g2))f_1 + f_2 \in O(\max(g_1, g_2)) and f1f2∈O(g1g2)f_1 f_2 \in O(g_1 g_2); if moreover g1∈O(h)g_1 \in O(h), then f1∈O(h)f_1 \in O(h). The same rules hold for Ω\Omega and Θ\Theta.

Proof. With f1≤c1g1f_1 \leq c_1 g_1 from n1n_1 on and f2≤c2g2f_2 \leq c_2 g_2 from n2n_2 on: from max⁡(n1,n2)\max(n_1, n_2) on, f1+f2≤(c1+c2)max⁡(g1,g2)f_1 + f_2 \leq (c_1 + c_2) \max(g_1, g_2) and f1f2≤c1c2 g1g2f_1 f_2 \leq c_1 c_2\, g_1 g_2. For transitivity, g1≤c hg_1 \leq c\,h from some rank on gives f1≤c1c hf_1 \leq c_1 c\, h. ∎

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 a>0a > 0 and b>1b > 1, as n→∞n \to \infty: log⁡n∈O(na)\log n \in O(n^a), na∈O(bn)n^a \in O(b^n) and bn∈O(n!)b^n \in O(n!), and none of these is a Θ\Theta. Moreover log⁡bn∈Θ(log⁡2n)\log_b n \in \Theta(\log_2 n), so the base of a logarithm does not matter inside OO.

Proof. The three limits recalled at the start of the chapter are 0, which gives each OO and excludes each Θ\Theta. And log⁡bn=log⁡2n/log⁡2b\log_b n = \log_2 n / \log_2 b 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
Output 13.2. The usual cost functions, and the two programs of the opening at thirty million records and a billion operations a second.
The usual cost functions on a logarithmic scale. Powers of n become straight lines of increasing slope on a log–log plot; here, with n on a linear axis, the exponential 2n is the straight line, and it crosses every power of n eventually.
The usual cost functions on a logarithmic scale. Powers of nn become straight lines of increasing slope on a log–log plot; here, with nn on a linear axis, the exponential 2n2^n is the straight line, and it crosses every power of nn eventually.

OO is only an upper bound. “Merge sort is in O(n3)O(n^3)” is true and useless; “insertion sort is in O(n2)O(n^2)” holds for every input, including the sorted ones that it finishes in n−1n - 1 comparisons. A lower bound needs Ω\Omega, and a precise statement needs Θ\Theta, 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 xx is C(x)C(x), and InI_n the finite set of inputs of size nn considered, the worst-case cost is max⁡x∈InC(x)\max_{x \in I_n} C(x), the best-case cost is min⁡x∈InC(x)\min_{x \in I_n} C(x), and the average-case cost is 1∣In∣∑x∈InC(x)\frac{1}{|I_n|}\sum_{x \in I_n} C(x).

For a comparison sort on distinct keys, only the order of the keys matters, so InI_n can be taken as the n!n! orders of 0,…,n−10, \dots, n - 1. For insertion sort, the best case is n−1n - 1 and the worst n(n−1)/2n(n - 1)/2; the average needs a count.

Proposition 13.7 (Average cost of insertion sort)

Over the n!n! orders of nn distinct keys, insertion sort makes on average exactly n(n−1)4+n−Hn\frac{n(n - 1)}{4} + n - H_n comparisons, where Hn=1+12+⋯+1nH_n = 1 + \frac12 + \dots + \frac1n. This is in Θ(n2)\Theta(n^2).

Proof. An inversion of an order is a pair of positions i<ji < j 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 II inversions and LL left-to-right minima (the first key counts) costs C=I+(n−1)−(L−1)C = I + (n - 1) - (L - 1).

Average of II: exchanging the keys at two positions i<ji < j is a one-to-one correspondence between the orders where the pair is inverted and those where it is not, so each of the (n2)\binom{n}{2} pairs is inverted in exactly half of the orders: the total of II is n!(n2)/2n! \binom{n}{2}/2, and the average n(n−1)/4n(n - 1)/4. Average of LL: position ii (from 0) holds a left-to-right minimum when it holds the smallest of the first i+1i + 1 keys; grouping the orders by the set of those keys and the arrangement of the rest, that smallest key is at each of the i+1i + 1 positions equally often, so in exactly 1/(i+1)1/(i + 1) of the orders. Summing over ii, the average of LL is HnH_n, and the average cost is n(n−1)/4+(n−1)−(Hn−1)n(n - 1)/4 + (n - 1) - (H_n - 1). As Hn≤nH_n \leq n, it lies between n(n−1)/4n(n - 1)/4 and n(n+3)/4n(n + 3)/4. ∎

$ 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
Output 13.3. The average over all orders, as an exact fraction, against the formula, for n≤8n \leq 8.

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 Θ(1)\Theta(1) cells beyond the list: it sorts in place. A merge sort that copies its halves uses Θ(n)\Theta(n) cells, and the recursion of a binary search uses Θ(log⁡n)\Theta(\log n) frames where the loop of Chapter 12 uses Θ(1)\Theta(1).

13.4 Sums

Nested loops give sums. A double loop over 0≤i<j<n0 \leq i < j < n performs (n2)=n(n−1)/2\binom{n}{2} = n(n - 1)/2 iterations; a triple loop over i<j<ki < j < k performs (n3)\binom{n}{3} (Exercise 13.7). A loop that doubles jj from 1 until nn runs ⌈log⁡2n⌉\lceil \log_2 n \rceil times. Three tools bound the sums that have no closed form.

Method 13.9 (Bounding a sum)

  1. Bound each term by the largest: ∑i=1nf(i)≤nmax⁡if(i)\sum_{i=1}^{n} f(i) \leq n \max_i f(i), an upper bound.
  2. Split: for ff increasing, the ⌈n/2⌉\lceil n/2 \rceil terms from i=⌊n/2⌋+1i = \lfloor n/2 \rfloor + 1 on are at least f(n/2)f(n/2), so ∑i=1nf(i)≥n2f(n2)\sum_{i=1}^n f(i) \geq \frac{n}{2} f(\frac{n}{2}), a lower bound of the same order as the upper one when f(n/2)∈Θ(f(n))f(n/2) \in \Theta(f(n)).
  3. Compare with an integral: for ff decreasing on [1,∞)[1, \infty), ∫1n+1f≤∑i=1nf(i)≤f(1)+∫1nf\int_1^{n + 1} f \leq \sum_{i=1}^n f(i) \leq f(1) + \int_1^n f.

Proposition 13.10 (Harmonic numbers and log⁡n!\log n!)

ln⁡(n+1)≤Hn≤1+ln⁡n\ln(n + 1) \leq H_n \leq 1 + \ln n, so Hn∈Θ(log⁡n)H_n \in \Theta(\log n); and log⁡2n!∈Θ(nlog⁡n)\log_2 n! \in \Theta(n \log n).

Proof. The integral of 1/x1/x from 1 to n+1n + 1 is ln⁡(n+1)\ln(n + 1), and from 1 to nn it is ln⁡n\ln n; the third rule gives the first claim. For the second, log⁡2n!=∑i=1nlog⁡2i≤nlog⁡2n\log_2 n! = \sum_{i=1}^n \log_2 i \leq n \log_2 n by the first rule, and ≥n2log⁡2n2=n2(log⁡2n−1)\geq \frac{n}{2} \log_2 \frac{n}{2} = \frac{n}{2}(\log_2 n - 1) by the second, which is at least n4log⁡2n\frac{n}{4}\log_2 n for n≥4n \geq 4. ∎

The harmonic number thus contributes only Θ(log⁡n)\Theta(\log n) to the average of insertion sort, and log⁡2n!\log_2 n! 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 T(n)T(n) 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. T(n)T(n) 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, T(n)=T(n/2)+1T(n) = T(n/2) + 1; merge sort sorts two halves and merges them with at most nn comparisons, T(n)=2T(n/2)+nT(n) = 2T(n/2) + n. Three methods solve them. Unrolling substitutes the equation into itself: T(n)=T(n/2)+1=T(n/4)+2=⋯=T(1)+log⁡2nT(n) = T(n/2) + 1 = T(n/4) + 2 = \dots = T(1) + \log_2 n for nn 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.

The recursion tree of T(n) = 2T(n/2) + n: every level costs n, and there are _2 n levels above the leaves, hence T(n) = n _2 n + nT(1) for n a power of 2.
The recursion tree of T(n)=2T(n/2)+nT(n) = 2T(n/2) + n: every level costs nn, and there are log⁡2n\log_2 n levels above the leaves, hence T(n)=nlog⁡2n+nT(1)T(n) = n\log_2 n + nT(1) for nn a power of 2.
$ 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
Output 13.4. Four recurrences computed exactly for nn a power of 2, each equal to its closed form: T1=log⁡2nT_1 = \log_2 n, T2=nlog⁡2nT_2 = n\log_2 n, T3=3nlog⁡23−2nT_3 = 3n^{\log_2 3} - 2n and T4=2n2−nT_4 = 2n^2 - n.

The forms of T3T_3 and T4T_4 come from the proof below; checking them by induction is short. For T4T_4: T4(1)=1=2−1T_4(1) = 1 = 2 - 1, and 4(2(n/2)2−n/2)+n=2n2−2n+n=2n2−n4(2(n/2)^2 - n/2) + n = 2n^2 - 2n + n = 2n^2 - n.

Theorem 13.12 (Master theorem)

Let a≥1a \geq 1, b≥2b \geq 2 an integer, k≥0k \geq 0, and TT defined on the powers of bb by T(1)>0T(1) > 0 and T(n)=aT(n/b)+nkT(n) = aT(n/b) + n^k. Then

T(n)∈{Θ(nk)if a<bk(the root dominates),Θ(nklog⁡n)if a=bk(every level costs the same),Θ(nlog⁡ba)if a>bk(the leaves dominate).T(n) \in \begin{cases} \Theta(n^k) & \text{if } a < b^k \quad\text{(the root dominates)},\\ \Theta(n^k \log n) & \text{if } a = b^k \quad\text{(every level costs the same)},\\ \Theta(n^{\log_b a}) & \text{if } a > b^k \quad\text{(the leaves dominate)}. \end{cases}

Proof. Let n=bmn = b^m. Unrolling, level ii of the recursion tree has aia^i nodes of size n/bin/b^i, each costing (n/bi)k(n/b^i)^k, and the ama^m leaves cost T(1)T(1) each:

T(n)=amT(1)+∑i=0m−1ai(nbi)k=amT(1)+nk∑i=0m−1qi,q=abk.T(n) = a^m T(1) + \sum_{i=0}^{m-1} a^i \Bigl(\frac{n}{b^i}\Bigr)^k = a^m T(1) + n^k \sum_{i=0}^{m-1} q^i, \qquad q = \frac{a}{b^k}.

Note that am=bmlog⁡ba=nlog⁡baa^m = b^{m \log_b a} = n^{\log_b a}. If a<bka < b^k, then q<1q < 1 and 1≤∑qi≤1/(1−q)1 \leq \sum q^i \leq 1/(1 - q); and log⁡ba<k\log_b a < k, so amT(1)≤T(1)nka^m T(1) \leq T(1) n^k; hence nk≤T(n)≤(T(1)+1/(1−q)) nkn^k \leq T(n) \leq (T(1) + 1/(1 - q))\, n^k. If a>bka > b^k, then q>1q > 1 and nk∑i<mqi=nk(qm−1)/(q−1)=(am−nk)/(q−1)n^k \sum_{i<m} q^i = n^k (q^m - 1)/(q - 1) = (a^m - n^k)/(q - 1), between 0 and am/(q−1)a^m/(q - 1); so T(1) am≤T(n)≤(T(1)+1/(q−1)) amT(1)\, a^m \leq T(n) \leq (T(1) + 1/(q - 1))\, a^m. The case a=bka = b^k is Exercise 13.10. ∎

Remark 13.13

Algorithms split nn into ⌊n/b⌋\lfloor n/b \rfloor and ⌈n/b⌉\lceil n/b \rceil parts, and their combining costs are c nkc\,n^k plus lower terms. The conclusions still hold for such recurrences when TT is increasing: T(n)T(n) lies between its values at the powers of bb around nn, 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
Listing 13.2. The three cases code/bachelor-1/13-asymptotic-analysis/listings/master.py
$ 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
Output 13.5. The cases on six recurrences, and the ratio of the exact T(n)T(n), with T(1)=1T(1) = 1, to the predicted order at 2102^{10} and 2202^{20}: it settles to a constant.

Karatsuba’s multiplication of nn-digit numbers replaces four half-size products by three, which moves the cost from Θ(n2)\Theta(n^2) to Θ(nlog⁡23)≈Θ(n1.585)\Theta(n^{\log_2 3}) \approx \Theta(n^{1.585}); Strassen’s product of matrices replaces eight half-size products by seven, from Θ(n3)\Theta(n^3) to Θ(n2.807)\Theta(n^{2.807}). Both are leaf-dominated: the count of subproblems matters more than the cost of combining them. The ratio for merge sort, 1+1/log⁡2n1 + 1/\log_2 n, shows how slowly the lower term fades.

The three regimes of the master theorem, drawn as the cost of each level of the recursion tree (one bar per level, from the root down). The level costs form a geometric sequence of ratio a/bk: decreasing, the root’s term dominates; constant, the _b n levels add up; increasing, the leaves dominate.
The three regimes of the master theorem, drawn as the cost of each level of the recursion tree (one bar per level, from the root down). The level costs form a geometric sequence of ratio a/bka/b^k: decreasing, the root’s term dominates; constant, the log⁡bn\log_b n levels add up; increasing, the leaves dominate.

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 nn and look at the ratio of the costs. For a cost c n2c\,n^2 plus lower terms the ratio tends to 4, for c nc\,n to 2, and for c nlog⁡2nc\,n \log_2 n it equals 2(1+1/log⁡2n)2(1 + 1/\log_2 n), slightly above 2 and tending to 2. The weekend problem proves these, and shows that a Θ\Theta class alone is not enough: a cost in Θ(n)\Theta(n) 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
Listing 13.3. Counts of three algorithms as nn doubles code/bachelor-1/13-asymptotic-analysis/listings/doubling.py
$ 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
Output 13.6. Comparisons of the maximum, merge sort and insertion sort on shuffled lists, then the ratios to the previous row.
$ 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
Output 13.7. The same three algorithms timed on the author’s laptop, best of five runs, in milliseconds, then the ratios.
Time divided by count, from the two outputs above: nearly flat for each algorithm, so the count predicts the time up to a constant, which differs between algorithms (a merge step allocates and appends, an insertion step only compares and moves).
Time divided by count, from the two outputs above: nearly flat for each algorithm, so the count predicts the time up to a constant, which differs between algorithms (a merge step allocates and appends, an insertion step only compares and moves).

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 n,2n,4n,…n, 2n, 4n, \dots 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)
Listing 13.4. Two counts code/bachelor-1/13-asymptotic-analysis/listings/exo_count.py
Solution

Solution of Exercise 13.1.

55
1024 10
Output 13.10. The two counts. Some lines are left out.

For each ii the inner loop runs 10−i10 - i times: 10+9+⋯+1=55=10⋅11/210 + 9 + \dots + 1 = 55 = 10 \cdot 11/2, in general n(n+1)/2n(n + 1)/2. The second loop doubles kk until it reaches 1000: k=210=1024k = 2^{10} = 1024 after 10 steps, in general ⌈log⁡2N⌉\lceil \log_2 N \rceil steps for a bound NN that is not a power of 2.

Exercise 13.2 ★

Order by growth, from slowest to fastest: n2log⁡nn^2 \log n, (log⁡n)10(\log n)^{10}, 1.01n1.01^n, n\sqrt{n}, n2.5n^{2.5}. Justify each step with Proposition 13.5.

Solution

Solution of Exercise 13.2.

(log⁡n)10≪n≪n2log⁡n≪n2.5≪1.01n(\log n)^{10} \ll \sqrt{n} \ll n^2 \log n \ll n^{2.5} \ll 1.01^n. First, (log⁡n)10/n=(log⁡n/n1/20)10→0(\log n)^{10}/\sqrt{n} = (\log n / n^{1/20})^{10} \to 0. Then n/(n2log⁡n)→0\sqrt{n}/(n^2 \log n) \to 0 trivially. Next n2log⁡n/n2.5=log⁡n/n0.5→0n^2 \log n / n^{2.5} = \log n / n^{0.5} \to 0. Last, n2.5/1.01n→0n^{2.5}/1.01^n \to 0 since 1.01>11.01 > 1.

Exercise 13.3 ★

With T(1)=1T(1) = 1 and T(n)=2T(n/2)+1T(n) = 2T(n/2) + 1, compute T(16)T(16), guess a closed form, and prove it.

Solution

Solution of Exercise 13.3.

T(2)=3T(2) = 3, T(4)=7T(4) = 7, T(8)=15T(8) = 15, T(16)=31T(16) = 31. Guess T(n)=2n−1T(n) = 2n - 1: true for n=1n = 1, and 2(2⋅n2−1)+1=2n−12(2 \cdot \frac n2 - 1) + 1 = 2n - 1. It is Θ(n)\Theta(n), the leaf case of the master theorem (a=2>20a = 2 > 2^0).

Exercise 13.4 ★

Which case of the master theorem applies, and what is the order of TT? (a) T(n)=4T(n/2)+nT(n) = 4T(n/2) + n. (b) T(n)=4T(n/2)+n2T(n) = 4T(n/2) + n^2. (c) T(n)=T(n/3)+nT(n) = T(n/3) + n. (d) T(n)=2T(n/4)+nT(n) = 2T(n/4) + \sqrt{n}.

Solution

Solution of Exercise 13.4.

(a) a=4>21a = 4 > 2^1: leaves, Θ(n2)\Theta(n^2). (b) a=4=22a = 4 = 2^2: even, Θ(n2log⁡n)\Theta(n^2 \log n). (c) a=1<31a = 1 < 3^1: root, Θ(n)\Theta(n). (d) k=12k = \frac12 and 41/2=2=a4^{1/2} = 2 = a: even, Θ(nlog⁡n)\Theta(\sqrt{n} \log n).

Exercise 13.5 ★★

Find the error. “We prove n2∈O(n)n^2 \in O(n) by induction on nn. For n=1n = 1, 1≤c⋅11 \leq c \cdot 1 with c=1c = 1. If n2≤cnn^2 \leq c n, then (n+1)2=n2+2n+1≤cn+3n=(c+3)n≤c′(n+1)(n + 1)^2 = n^2 + 2n + 1 \leq cn + 3n = (c + 3)n \leq c'(n + 1) with c′=c+3c' = c + 3. So n2∈O(n)n^2 \in O(n).”

Solution

Solution of Exercise 13.5.

The statement n2∈O(n)n^2 \in O(n) asks for one constant cc valid for all large nn. The “induction” proves n2≤cnnn^2 \leq c_n n with a constant that grows at each step: c1=1c_1 = 1, cn+1=cn+3c_{n + 1} = c_n + 3, so cn=3n−2c_n = 3n - 2. What it proves is n2≤(3n−2)nn^2 \leq (3n - 2)n, which is true and says nothing. An induction for a OO statement must keep the same constant in the hypothesis and the conclusion, and here it cannot: n2/n=nn^2/n = n is unbounded.

Exercise 13.6 ★★

A student reasons: “the inner loop runs at most log⁡2n\log_2 n times, so the function costs Θ(nlog⁡n)\Theta(n \log n)”. 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
Listing 13.5. A loop that depends on ii code/bachelor-1/13-asymptotic-analysis/listings/exo_cost.py
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
Output 13.8. The counts. Some lines are left out.
Solution

Solution of Exercise 13.6.

The bound O(nlog⁡n)O(n \log n) is right, but it is not a Θ\Theta: the inner loop runs log⁡2n\log_2 n times only for small ii. For a given ii it runs ⌈log⁡2(n/i)⌉\lceil \log_2 (n/i) \rceil times, and at least tt times exactly when i⋅2t−1<ni \cdot 2^{t - 1} < n, for fewer than n/2t−1n/2^{t - 1} values of ii. Summing over t≥1t \geq 1, the count is below n(1+12+14+⋯ )=2nn(1 + \frac12 + \frac14 + \cdots) = 2n; and it is at least n−1n - 1, since each i<ni < n runs once. So the cost is Θ(n)\Theta(n), and the output shows count/n\text{count}/n approaching 2 while count/(nlog⁡2n)\text{count}/(n \log_2 n) tends to 0.

Exercise 13.7 ★★

Write count_triples(n), which counts the iterations of three nested loops over 0≤i<j<k<n0 \leq i < j < k < n. 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
Three nested loops code/bachelor-1/13-asymptotic-analysis/exercises/nested_count.py

Each iteration corresponds to one set {i,j,k}\{i, j, k\} of three distinct indices written in increasing order, and each such set to one iteration: there are (n3)=n(n−1)(n−2)/6\binom{n}{3} = n(n - 1)(n - 2)/6 of them, in Θ(n3)\Theta(n^3). The test compares the counter with the formula for n<12n < 12.

Exercise 13.8 ★★

Prove that ∑i=1nilog⁡2i∈Θ(n2log⁡n)\sum_{i=1}^n i \log_2 i \in \Theta(n^2 \log n).

Solution

Solution of Exercise 13.8.

Upper bound: each term is at most nlog⁡2nn \log_2 n, so the sum is at most n2log⁡2nn^2 \log_2 n. Lower bound: the terms with i≥n/2i \geq n/2, at least n/2n/2 of them, are at least n2log⁡2n2\frac n2 \log_2 \frac n2, so the sum is at least n24(log⁡2n−1)≥n28log⁡2n\frac{n^2}{4}(\log_2 n - 1) \geq \frac{n^2}{8} \log_2 n for n≥4n \geq 4.

Exercise 13.9 ★★

Solve exactly T(0)=0T(0) = 0, T(n)=T(n−1)+nT(n) = T(n - 1) + n, and U(0)=0U(0) = 0, U(n)=2U(n−1)+1U(n) = 2U(n - 1) + 1. Why does the master theorem not apply?

Solution

Solution of Exercise 13.9.

T(n)=1+2+⋯+n=n(n+1)/2T(n) = 1 + 2 + \dots + n = n(n + 1)/2. For UU, U(n)+1=2(U(n−1)+1)U(n) + 1 = 2(U(n - 1) + 1), so U(n)+1=2nU(n) + 1 = 2^n and U(n)=2n−1U(n) = 2^n - 1; both closed forms follow by induction, and the test checks them to n=59n = 59. The master theorem covers subproblems of size n/bn/b, a constant fraction of nn; here the size decreases by 1, and the recursion tree has nn levels instead of log⁡bn\log_b n.

Exercise 13.10 ★★★

Prove the case a=bka = b^k of Theorem 13.12: give T(n)T(n) exactly for n=bmn = b^m, and deduce T(n)∈Θ(nklog⁡n)T(n) \in \Theta(n^k \log n).

Solution

Solution of Exercise 13.10.

With q=a/bk=1q = a/b^k = 1, the sum is m=log⁡bnm = \log_b n and am=nlog⁡ba=nka^m = n^{\log_b a} = n^k, so T(n)=nk(T(1)+log⁡bn)T(n) = n^k (T(1) + \log_b n) exactly. For n≥bn \geq b, log⁡bn≥1\log_b n \geq 1, so nklog⁡bn≤T(n)≤(T(1)+1) nklog⁡bnn^k \log_b n \leq T(n) \leq (T(1) + 1)\, n^k \log_b n: T(n)∈Θ(nklog⁡n)T(n) \in \Theta(n^k \log n), the base of the logarithm being irrelevant.

Exercise 13.11 ★★★

Let T(1)=0T(1) = 0 and T(n)=T(⌊n/2⌋)+T(⌈n/2⌉)+nT(n) = T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + n for n≥2n \geq 2. Prove that TT is increasing and that T(n)∈Θ(nlog⁡n)T(n) \in \Theta(n \log n); then check that T(n)=n⌈log⁡2n⌉+n−2⌈log⁡2n⌉T(n) = n\lceil \log_2 n \rceil + n - 2^{\lceil \log_2 n \rceil} for every n≥1n \geq 1.

Solution

Solution of Exercise 13.11.

Increasing, by strong induction: T(2)=2>T(1)T(2) = 2 > T(1); for n≥2n \geq 2, ⌊(n+1)/2⌋≥⌊n/2⌋\lfloor (n + 1)/2 \rfloor \geq \lfloor n/2 \rfloor and ⌈(n+1)/2⌉≥⌈n/2⌉\lceil (n + 1)/2 \rceil \geq \lceil n/2 \rceil, all four at most nn, so by the hypothesis T(n+1)≥T(n)+1T(n + 1) \geq T(n) + 1. Order: for 2m−1<n≤2m2^{m - 1} < n \leq 2^m, T(n)≤T(2m)=m2m≤2n(log⁡2n+1)T(n) \leq T(2^m) = m 2^m \leq 2n(\log_2 n + 1) and T(n)≥T(2m−1)=(m−1)2m−1≥n2(log⁡2n−1)T(n) \geq T(2^{m - 1}) = (m - 1)2^{m - 1} \geq \frac n2 (\log_2 n - 1), using the power-of-2 values T(2m)=m2mT(2^m) = m 2^m of Output 13.4. So T(n)∈Θ(nlog⁡n)T(n) \in \Theta(n \log n). Exact form: the test checks T(n)=n⌈log⁡2n⌉+n−2⌈log⁡2n⌉T(n) = n\lceil \log_2 n \rceil + n - 2^{\lceil \log_2 n \rceil} for every n<3000n < 3000, and also nlog⁡2n≤T(n)≤nlog⁡2n+nn \log_2 n \leq T(n) \leq n \log_2 n + n.

Exercise 13.12 ★★★

Write identify(a, b, k), which computes T(bi)T(b^i) for T(n)=aT(n/b)+nkT(n) = aT(n/b) + n^k and T(1)=1T(1) = 1, estimates the exponent of TT from the numbers, and says which case of the master theorem the numbers show, without using the comparison of aa with bkb^k. 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
Reading the case from the numbers code/bachelor-1/13-asymptotic-analysis/exercises/solve_rec.py

The values T(bi)T(b^i) follow the recurrence directly, as integers. The ratio of the last two values is about beb^e for T∈Θ(ne)T \in \Theta(n^e), and about bk(1+1/m)b^k(1 + 1/m) in the even case: an exponent clearly above kk means the leaves dominate. Otherwise the quotient T(n)/nkT(n)/n^k distinguishes the two other cases: it grows by about one per level in the even case (it is T(1)+log⁡bnT(1) + \log_b n) 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 nn 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
Listing 13.6. Three ways to find the duplicates code/bachelor-1/13-asymptotic-analysis/listings/duplicates.py
$ 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
Output 13.9. The number of duplicated books, the counts, and their ratios as nn doubles.

Part I — The double loop.

  1. Show that by_pairs makes exactly n(n−1)/2n(n - 1)/2 comparisons, whatever the data.
  2. Deduce that it is in Θ(n2)\Theta(n^2), in the best, the worst and the average case.
  3. Check the column pairs of the table.
  4. Compute the ratio of the counts for 2n2n and nn, and its limit.
  5. Could the function stop early? Rewrite its specification so that it can (“is there a duplicate?”), and give its best and worst cases then.
  6. What is its space cost, beyond the input and the answer?

Part II — Sort, then scan.

  1. Show that after sorting, two equal values are neighbours, and that the scan finds every duplicated value.
  2. Merge sort makes at most T(n)T(n) comparisons, with T(1)=0T(1) = 0 and T(n)=T(⌊n/2⌋)+T(⌈n/2⌉)+n−1T(n) = T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + n - 1. Show that T(n)≤n⌈log⁡2n⌉T(n) \leq n \lceil \log_2 n \rceil.
  3. Deduce that by_sorting is in O(nlog⁡n)O(n \log n).
  4. On the table, compare the counts with nlog⁡2nn \log_2 n for n=400n = 400.
  5. Show that (2n)log⁡2(2n)/(nlog⁡2n)=2(1+1/log⁡2n)(2n)\log_2(2n) / (n \log_2 n) = 2(1 + 1/\log_2 n), and compute it for n=25n = 25 and n=200n = 200.
  6. Why are the measured ratios not exactly these values?

Part III — A set of seen values.

  1. Show that by_set makes exactly nn look-ups.
  2. Under which assumption on the set is its cost in Θ(n)\Theta(n)? (Hash tables are studied in Chapter 16.)
  3. What is the space cost of each of the three methods?
  4. 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.
  5. For n=400n = 400, how many times fewer operations does the set make than the double loop?
  6. Why does the table count only one operation per look-up, when a look-up does several elementary operations?

Part IV — The doubling ratio.

  1. For a cost f(n)=c nkf(n) = c\,n^k, show that f(2n)/f(n)=2kf(2n)/f(n) = 2^k exactly.
  2. For f(n)=c nk+d nk−1f(n) = c\, n^k + d\,n^{k - 1} with c>0c > 0, show that the ratio tends to 2k2^k.
  3. For f∈Θ(g)f \in \Theta(g) only, can the ratio of ff fail to converge? Give an example.
  4. Read the ratios of the table, and say which order each column suggests.
  5. Why do the ratios of the merge sort column approach 2 so slowly?
  6. State the named result of the problem, the doubling ratio test: the limits of the ratios for counts c n2c\,n^2, c nlog⁡2nc\,n \log_2 n and c nc\,n, proved, and the values read from the table.
Solution

Solution of Problem 13.1.

1. For each ii the inner loop runs n−1−in - 1 - i times: (n−1)+(n−2)+⋯+0=n(n−1)/2(n - 1) + (n - 2) + \dots + 0 = n(n - 1)/2, independent of the values.

2. Every input of size nn costs the same, so the three cases coincide, in Θ(n2)\Theta(n^2).

3. 25⋅24/2=30025 \cdot 24/2 = 300, 12251225, 49504950, 19 90019\,900 and 400⋅399/2=79 800400 \cdot 399/2 = 79\,800.

4. 2n(2n−1)n(n−1)=2(2n−1)n−1→4\frac{2n(2n - 1)}{n(n - 1)} = \frac{2(2n - 1)}{n - 1} \to 4; for n=25n = 25 it is 1225/300≈4.081225/300 \approx 4.08.

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, n(n−1)/2n(n - 1)/2 comparisons.

6. Θ(1)\Theta(1): 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 c=⌈log⁡2n⌉c = \lceil \log_2 n \rceil: since n≤2cn \leq 2^c, both halves have at most 2c−12^{c - 1} elements, so T(n)≤⌊n2⌋(c−1)+⌈n2⌉(c−1)+n−1<ncT(n) \leq \lfloor \frac n2 \rfloor (c - 1) + \lceil \frac n2 \rceil (c - 1) + n - 1 < nc.

9. At most n⌈log⁡2n⌉n \lceil \log_2 n \rceil comparisons to sort and n−1n - 1 to scan: O(nlog⁡n)O(n \log n).

10. 400log⁡2400≈3458400 \log_2 400 \approx 3458; 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. 2nlog⁡2(2n)nlog⁡2n=2(log⁡2n+1)log⁡2n\frac{2n \log_2 (2n)}{n \log_2 n} = \frac{2(\log_2 n + 1)}{\log_2 n}. For n=25n = 25: 2(1+1/4.64)≈2.432(1 + 1/4.64) \approx 2.43; for n=200n = 200: 2(1+1/7.64)≈2.262(1 + 1/7.64) \approx 2.26. The table shows 2.46 and 2.28.

12. The counts are not exactly c nlog⁡2nc\,n \log_2 n: the merges depend on the data, and the scan adds a linear term.

13. One look-up per element of the list: nn.

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 Θ(1)\Theta(1); sorting Θ(n)\Theta(n), for the copies made by merge sort; the set as many cells as there are distinct values, at most nn (here at most 80).

16. seen = [False] * 81; for each x, test and set seen[x]: nn steps of constant cost, plus 81 to create the list, Θ(n)\Theta(n) time and Θ(1)\Theta(1) space for a fixed range of identifiers.

17. 79 800/400≈20079\,800/400 \approx 200 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 Θ\Theta ignores.

19. c(2n)k/(c nk)=2kc(2n)^k/(c\,n^k) = 2^k.

20. Dividing numerator and denominator by nkn^k: c 2k+d 2k−1/nc+d/n→2k\frac{c\,2^k + d\,2^{k - 1}/n}{c + d/n} \to 2^k.

21. Yes. f(n)=nf(n) = n when ⌊log⁡2n⌋\lfloor \log_2 n \rfloor is even and 3n3n when it is odd is in Θ(n)\Theta(n), but f(2n)/f(n)f(2n)/f(n) alternates between 6 and 2/32/3.

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, nlog⁡nn \log n; set: exactly 2.00, linear.

23. The excess 2/log⁡2n2/\log_2 n decreases like a logarithm: it is still 0.2 at n=1024n = 1024 and 0.1 at about a million.

24. The doubling ratio test: when nn doubles, the ratio of the counts tends to 4 for c n2c\,n^2 (question 19), to 2 for c nc\,n, and equals 2(1+1/log⁡2n)2(1 + 1/\log_2 n) for c nlog⁡2nc\,n \log_2 n (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: Θ(n2)\Theta(n^2), Θ(nlog⁡n)\Theta(n \log n) and Θ(n)\Theta(n). The test is a diagnosis, not a proof: question 21 shows a Θ(n)\Theta(n) cost whose ratio never settles.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো