Salta al contenuto
Note per Studenti Analysis of Algorithms and Asymptotic Notation Report

Analysis of Algorithms and Asymptotic Notation

In questa pagina 11

What is analysed

The analysis of an algorithm AA studies its efficiency and effectiveness:

Examples: a search engine is successful not only for correct results but for being very fast (time); an embedded system must fit in strict memory limits (space).

Why not measure running time?

The running time of a program depends on the input instance (it usually grows with size, but instances of the same size can differ a lot, e.g. InsertionSort), on the hardware and on the software environment. Measuring it in Java with System.currentTimeMillis() before and after the run is possible but:

  • it needs a full implemented program (a lot of work);
  • comparing algorithms is difficult (implementation details matter);
  • it depends strongly on hardware and software;
  • it covers only the inputs actually tried.

Requirements for a better method:

  1. account for all possible inputs;
  2. allow comparing algorithms without computing exact times;
  3. work from a high-level specification (pseudocode).

Approach:

Worst-case time complexity

Let AA solve Π⊆I×S\Pi \subseteq \mathcal{I} \times S. Let tA,it_{A,i} be the number of operations of AA on instance ii. The worst-case time complexity is

tA(n)=max⁡{ tA,i:i∈I, size(i)=n }t_A(n) = \max\{\, t_{A,i} : i \in \mathcal{I},\ \text{size}(i) = n \,\}

the maximum number of operations on an instance of size nn ("operations" = elementary RAM steps). More precisely tAt_A is a function of whichever parameter(s) describe the size.

Why exact tA(n)t_A(n) is not needed

Computing it is often very hard, if not impossible: it is hard to find the worst instance of size nn and to count its operations (this would need a detailed definition of the elementary steps). And it is not necessary:

  • the choice of elementary steps is not uniform across architectures;
  • real running time depends on many software/hardware factors that cannot be quantified.

So we settle for bounds: functions f1,f2f_1, f_2 with tA(n)≤f1(n)t_A(n) \le f_1(n) (upper) and tA(n)≥f2(n)t_A(n) \ge f_2(n) (lower), without having to identify the worst-case instance. The quality of the estimate depends on how close the bounds are to the true value.

Three kinds of limit on the complexity of an instance ii of size nn:

  • tUt_U: upper bound, tA,i≤tUt_{A,i} \le t_U for every ii (so also bounds tA(n)t_A(n) from above);
  • tlt_l: lower bound valid for every instance, tA,i≥tlt_{A,i} \ge t_l for all ii (the algorithm systematically takes at least this many operations);
  • tLt_L: lower bound for at least one instance, ∃i:tA,i≥tL\exists i : t_{A,i} \ge t_L (sometimes the algorithm takes at least this many).

Both tlt_l and tLt_L are lower bounds on the worst case tA(n)t_A(n).

Example: arrayMax

Algorithm arrayMax(A)
Input: array A[0 ÷ n-1] of n ≥ 1 integers
Output: max integer in A
currMax ← A[0];
for i ← 1 to n-1 do {
    if (currMax < A[i]) then currMax ← A[i];
}
return currMax

Size: nn. For any instance of size nn:

  • outside the loop a constant number of operations (constant with respect to nn);
  • the loop makes n−1n-1 iterations, each with a constant number of operations (the if may cost more or less depending on whether the condition is true, but the cost is bounded by a constant).

So there are constants c1,c2,c3,c4>0c_1, c_2, c_3, c_4 > 0 such that for every nn:

c3n+c4≤tarrayMax(n)≤c1n+c2c_3 n + c_4 \le t_{\text{arrayMax}}(n) \le c_1 n + c_2

  • c1,c3c_1, c_3 bound the cost per iteration from above and below; c2,c4c_2, c_4 bound the cost outside the loop.
  • The loop is proportional to n−1n-1, approximated with nn.
  • "Constant" means independent of the input size, not small (it can be 210002^{1000}).

The constants are not estimated: counting operations exactly is hard, the set of operations is arbitrary and machine-dependent, and execution time depends on too many factors. Hence the asymptotic analysis: drop multiplicative constants (c1n+c2→n+c2c_1 n + c_2 \to n + c_2) and non-dominant additive terms (n+c2→nn + c_2 \to n). Here upper and lower bound coincide: tarrayMaxt_{\text{arrayMax}} is proportional to nn, i.e. linear.

Asymptotic notation

Let f(n),g(n)f(n), g(n) map N∪{0}\mathbb{N} \cup \{0\} to non-negative reals. The notations O,Ω,Θ,oO, \Omega, \Theta, o express asymptotic bounds; the orders of growth (1,n,n2,…1, n, n^2, \dots) are the reference functions gg.

Notation Meaning
O(⋅)O(\cdot) big-oh upper bound
Ω(⋅)\Omega(\cdot) big-omega lower bound
Θ(⋅)\Theta(\cdot) big-theta tight bound
o(⋅)o(\cdot) little-oh strict upper bound

Big-O

f(n)∈O(g(n))  ⟺  ∃ c>0, n0≥1 constants such that f(n)≤c g(n)  ∀n≥n0f(n) \in O(g(n)) \iff \exists\, c > 0,\ n_0 \ge 1 \text{ constants such that } f(n) \le c\, g(n)\ \ \forall n \ge n_0

From n0n_0 on, ff grows no faster than c⋅gc \cdot g.

How to prove it (example f(n)=3n+4f(n) = 3n + 4, n≥1n \ge 1):

  1. Take gg = dominant term: g(n)=ng(n) = n.
  2. Rewrite the constant as a multiple of the dominant term: 3n+4≤3n+4n=7n3n + 4 \le 3n + 4n = 7n.
  3. Find when the inequality holds: 4≤4n4 \le 4n for n≥1n \ge 1, so n0=1n_0 = 1.

Hence 3n+4∈O(n)3n + 4 \in O(n) with c=7c = 7, n0=1n_0 = 1. Other choices work too (e.g. n0=4n_0 = 4, c=4c = 4). Also 3n+4∈O(n2)3n + 4 \in O(n^2), but the tightest bound (O(n)O(n)) is preferred.

f(n)f(n) O(g)O(g) cc n0n_0
3n+43n + 4 O(n)O(n) 7 1
n+2n2n + 2n^2 O(n2)O(n^2) 3 1
21002^{100} O(1)O(1) 21002^{100} 1
c1n+c2c_1 n + c_2 (c1,c2>0c_1, c_2 > 0) O(n)O(n) c1+c2c_1 + c_2 1

Big-Omega

f(n)∈Ω(g(n))  ⟺  ∃ c>0, n0≥1 such that f(n)≥c g(n)  ∀n≥n0f(n) \in \Omega(g(n)) \iff \exists\, c > 0,\ n_0 \ge 1 \text{ such that } f(n) \ge c\, g(n)\ \ \forall n \ge n_0

For 3n+43n + 4: drop the positive constant, 3n+4≥3n3n + 4 \ge 3n, so c=3c = 3, n0=1n_0 = 1 and 3n+4∈Ω(n)3n+4 \in \Omega(n).

f(n)f(n) Ω(g)\Omega(g) cc n0n_0
3n+43n + 4 Ω(n)\Omega(n) 3 1
n+2n2n + 2n^2 Ω(n2)\Omega(n^2) 2 1
21002^{100} Ω(1)\Omega(1) 1 1
c3n+c4c_3 n + c_4 Ω(n)\Omega(n) c3c_3 1

Big-Theta

f(n)∈Θ(g(n))  ⟺  f(n)∈O(g(n)) and f(n)∈Ω(g(n))f(n) \in \Theta(g(n)) \iff f(n) \in O(g(n)) \text{ and } f(n) \in \Omega(g(n))

i.e. ∃ c′,c′′>0, n0≥1\exists\, c', c'' > 0,\ n_0 \ge 1: c′ g(n)≤f(n)≤c′′ g(n)c'\, g(n) \le f(n) \le c''\, g(n) for all n≥n0n \ge n_0. So 3n+4∈Θ(n)3n + 4 \in \Theta(n), n+2n2∈Θ(n2)n + 2n^2 \in \Theta(n^2), 2100∈Θ(1)2^{100} \in \Theta(1), tarrayMax(n)∈Θ(n)t_{\text{arrayMax}}(n) \in \Theta(n).

Little-o

f(n)∈o(g(n))  ⟺  ∀ c>0 ∃ n0≥1:f(n)≤c g(n)  ∀n≥n0  ⟺  lim⁡n→+∞f(n)g(n)=0f(n) \in o(g(n)) \iff \forall\, c > 0\ \exists\, n_0 \ge 1 : f(n) \le c\, g(n)\ \ \forall n \ge n_0 \iff \lim_{n \to +\infty} \frac{f(n)}{g(n)} = 0

Big-O needs some constant cc, little-o needs every c>0c > 0, however small: it is a stronger statement. Here n0n_0 usually depends on cc.

Examples: 100n∈o(n2)100 n \in o(n^2) (since 100n/n2→0100n / n^2 \to 0); 3nlog⁡2n∈o(n)\dfrac{3n}{\log_2 n} \in o(n) for n≥2n \ge 2.

Properties of growth rates

  • Polynomials. If p(n)=∑i=0kainip(n) = \sum_{i=0}^{k} a_i n^i with ak>0a_k > 0, k≥0k \ge 0, then p(n)∈Θ(nk)p(n) \in \Theta(n^k). Example: (n+1)5∈Θ(n5)(n+1)^5 \in \Theta(n^5) (expanding gives a polynomial of degree 5 with positive leading coefficient).
  • Logarithms. For constants a,b>1a, b > 1, log⁡bn∈Θ(log⁡an)\log_b n \in \Theta(\log_a n), because log⁡bn=log⁡ba⋅log⁡an\log_b n = \log_b a \cdot \log_a n and log⁡ba\log_b a is a constant. So the base is omitted inside asymptotic notation; outside it, the base is assumed to be 2.
  • Exponential vs polynomial. nk∈o(an)n^k \in o(a^n) for constants k>0k > 0, a>1a > 1. Exponential time is always worse than polynomial time.
  • Polylogarithmic vs polynomial. (log⁡bn)k∈o(nh)(\log_b n)^k \in o(n^h) for constants b>1b > 1, h,k>0h, k > 0.

Typical growth rates

Class Notation
logarithmic Θ(log⁡n)\Theta(\log n)
polylogarithmic Θ((log⁡n)k)\Theta((\log n)^k), k>0k > 0
linear Θ(n)\Theta(n)
polynomial Θ(nk)\Theta(n^k), k>0k > 0 (quadratic n2n^2, cubic n3n^3, ...)
exponential Ω(an)\Omega(a^n), a>1a > 1

Remark: for exponentials we write Ω(an)\Omega(a^n) because the exact growth depends on the base (2n∉Θ(3n)2^n \notin \Theta(3^n)).

Mathematical tools

Complexity analysis in practice

To prove tA(n)∈O(f(n))t_A(n) \in O(f(n)): show that for all sufficiently large nn and every instance of size nn, tA(n)≤cf(n)t_A(n) \le c f(n) for some constant c>0c > 0. The algorithm performs at most cf(n)c f(n) operations.

  • The proof must hold for all instances, with no assumption on a particular one.
  • "Sufficiently large" means n≥n0n \ge n_0; n0n_0 need not be computed.
  • cc need not be computed; it suffices to prove it exists.

To prove tA(n)∈Ω(f(n))t_A(n) \in \Omega(f(n)):

  • v.1: for all sufficiently large nn there exists at least one instance of size nn with tA(n)≥cf(n)t_A(n) \ge c f(n) (this is tLt_L);
  • v.2: for every instance of size nn the algorithm performs ≥cf(n)\ge c f(n) operations (this is tlt_l).
  • For v.1 the proof must exhibit (the existence of) one such instance.

To get Θ\Theta: prove both O(f(n))O(f(n)) and Ω(f(n))\Omega(f(n)).

Guidelines: f(n)f(n) must be as tight as possible (close to the true complexity) and as simple as possible (no constants, no lower-order additive terms). An upper bound guarantees the algorithm is never worse than the limit; if it is too loose, a lower bound confines the complexity between two limits. The goal is matching bounds: Θ(f(n))\Theta(f(n)).

Example: prefixAverages

Given X[0,…,n−1]X[0, \dots, n-1], compute A[0,…,n−1]A[0, \dots, n-1] with

A[i]=1i+1∑j=0iX[j]0≤i<nA[i] = \frac{1}{i+1} \sum_{j=0}^{i} X[j] \qquad 0 \le i < n

i.e. A[i]A[i] is the mean of the first i+1i+1 elements. Two algorithms (code reconstructed from the slide annotations).

prefixAverages1: the straightforward one, from the definition.

Algorithm prefixAverages1
Input: X[0, …, n-1] array of n integers
Output: A[0, …, n-1] array: A[i] = (1/(i+1)) · sum_{j=0..i} X[j]
for i ← 0 to n-1 do {
    a ← 0;                          // a: accumulator for the sum
    for j ← 0 to i do               // inner loop: accumulates up to index i
        a ← a + X[j];
    A[i] ← a / (i+1);               // accumulated value divided by (i+1)
}
return A

Inefficient: every iteration recomputes partial sums from scratch. Cost: outer loop nn iterations, inner loop i+1i + 1 iterations with Θ(1)\Theta(1) operations each, plus Θ(1)\Theta(1) work per outer iteration:

Θ ⁣(∑i=0n−1(i+1))=Θ ⁣(∑i=1ni)=Θ ⁣(n(n+1)2)=Θ(n2)\Theta\!\left(\sum_{i=0}^{n-1} (i+1)\right) = \Theta\!\left(\sum_{i=1}^{n} i\right) = \Theta\!\left(\frac{n(n+1)}{2}\right) = \Theta(n^2)

(Gauss' formula). True for every instance, so the bound is tight: tA1(n)∈Θ(n2)t_{A_1}(n) \in \Theta(n^2).

prefixAverages2: reuse the previous sum.

Algorithm prefixAverages2
Input: X[0, …, n-1] array of n integers
Output: A[0, …, n-1] array: A[i] = (1/(i+1)) · sum_{j=0..i} X[j]
a ← 0;                              // external accumulator
for i ← 0 to n-1 do {
    a ← a + X[i];                   // add the new element
    A[i] ← a / (i+1);
}
return A

The loop runs nn times with a constant number of operations (independent of ii) for every instance: tA2(n)∈Θ(n)t_{A_2}(n) \in \Theta(n). It is more efficient than prefixAverages1.

General rule of efficiency: if an algorithm repeats the same computation many times it wastes time; store intermediate results and reuse them.

Exercise: c1nc_1 n for even, c2⌈log⁡2n⌉c_2 \lceil \log_2 n \rceil for odd

AA receives an array XX of n≥1n \ge 1 integers and performs c1nc_1 n operations for each even integer and c2⌈log⁡2n⌉c_2 \lceil \log_2 n \rceil for each odd integer (c1,c2>0c_1, c_2 > 0). Size: nn. Note n≥⌈log⁡2n⌉n \ge \lceil \log_2 n \rceil for all n≥1n \ge 1. Intuition: nn even elements cost n2n^2.

Upper bound (every instance):

#op≤n⋅max⁡{c1n, c2⌈log⁡2n⌉}≤n⋅max⁡{c1,c2}⋅max⁡{n,⌈log⁡2n⌉}=max⁡{c1,c2} n2\#\text{op} \le n \cdot \max\{c_1 n,\ c_2 \lceil \log_2 n \rceil\} \le n \cdot \max\{c_1, c_2\} \cdot \max\{n, \lceil \log_2 n \rceil\} = \max\{c_1, c_2\}\, n^2

so tA(n)∈O(n2)t_A(n) \in O(n^2).

Lower bound, v.2 (every instance):

#op≥n⋅min⁡{c1n, c2⌈log⁡2n⌉}≥n⋅min⁡{c1,c2}⋅⌈log⁡2n⌉\#\text{op} \ge n \cdot \min\{c_1 n,\ c_2 \lceil \log_2 n \rceil\} \ge n \cdot \min\{c_1, c_2\} \cdot \lceil \log_2 n \rceil

so tA(n)∈Ω(nlog⁡n)t_A(n) \in \Omega(n \log n). Valid for all instances but not tight: instances with only odd numbers cost just c2 n⌈log⁡2n⌉c_2\, n \lceil \log_2 n \rceil.

Lower bound, v.1 (one instance): the instance with nn even elements costs c1n2c_1 n^2, so tA(n)∈Ω(n2)t_A(n) \in \Omega(n^2).

Tight bound: O(n2)O(n^2) and Ω(n2)\Omega(n^2) give tA(n)∈Θ(n2)t_A(n) \in \Theta(n^2).

Comparing algorithms and efficiency

For algorithms A,BA, B solving the same problem Π\Pi: if tA(n)∈o(tB(n))t_A(n) \in o(t_B(n)), then AA is asymptotically more efficient than BB (n0n_0 could be very large). Rule of thumb: polynomial (or better) is efficient, exponential is not. Why exponential is bad, and the caveats on asymptotic worst-case analysis, are in Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants → (section on executable size).

Versione ripasso

  • Analysis: time (our focus) and space; correctness = termination + solves the problem.
  • Worst case: tA(n)=max⁡{tA,i:size(i)=n}t_A(n) = \max\{t_{A,i} : \text{size}(i) = n\}, counted in RAM elementary steps. Exact value is hard and unnecessary, so use bounds: tUt_U (all instances), tlt_l (all instances, lower), tLt_L (at least one instance, lower).
  • Definitions (∃ c>0, n0≥1\exists\, c>0,\ n_0 \ge 1, ∀n≥n0\forall n \ge n_0):
    • f∈O(g)f \in O(g): f(n)≤c g(n)f(n) \le c\,g(n) (upper);
    • f∈Ω(g)f \in \Omega(g): f(n)≥c g(n)f(n) \ge c\,g(n) (lower);
    • f∈Θ(g)f \in \Theta(g): both (tight);
    • f∈o(g)f \in o(g): for every c>0c > 0 (strict), equivalently f/g→0f/g \to 0.
  • Proving OO: 3n+4≤3n+4n=7n3n + 4 \le 3n + 4n = 7n, n0=1n_0 = 1. Proving Ω\Omega: 3n+4≥3n3n + 4 \ge 3n. Prefer the tightest, simplest gg (no constants or lower-order terms).
  • Properties: polynomial of degree kk is Θ(nk)\Theta(n^k); log⁡bn∈Θ(log⁡an)\log_b n \in \Theta(\log_a n) (base omitted, default 2); nk∈o(an)n^k \in o(a^n); (log⁡n)k∈o(nh)(\log n)^k \in o(n^h).
  • Classes: log⁡n\log n, (log⁡n)k(\log n)^k, nn, nkn^k, exponential Ω(an)\Omega(a^n).
  • Tools: floor, ceiling, mod, Gauss ∑j=0nj=n(n+1)/2\sum_{j=0}^{n} j = n(n+1)/2, geometric series.
  • In practice: OO must hold for every instance; Ω\Omega v.1 needs one bad instance, v.2 holds for all; Θ\Theta = OO + Ω\Omega.
  • arrayMax: constant outside + n−1n-1 iterations of constant cost, so Θ(n)\Theta(n).
  • prefixAverages: v1 nested loops Θ(∑(i+1))=Θ(n2)\Theta(\sum (i+1)) = \Theta(n^2); v2 running sum Θ(n)\Theta(n). Rule: store and reuse partial results.
  • Exercise (c1nc_1 n even, c2⌈log⁡2n⌉c_2 \lceil \log_2 n \rceil odd): O(n2)O(n^2) by max⁡\max, Ω(nlog⁡n)\Omega(n\log n) for all instances, Ω(n2)\Omega(n^2) from the all-even instance, so Θ(n2)\Theta(n^2).
  • Typical mistakes: proving OO on one instance only; calling a loose OO the complexity; saying "constant" means small; confusing oo with OO; keeping the log base inside Θ\Theta.
  • See Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants → and Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →.

Teoria collegata