Analysis of Algorithms and Asymptotic Notation
In questa pagina 11
What is analysed
The analysis of an algorithm studies its efficiency and effectiveness:
- Complexity: time (how fast it produces the result, our focus) and space (how much memory it needs, e.g. in sensors or embedded systems).
- Correctness: termination (no infinite loops) and solution (it solves the intended problem, not just stops). 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 →.
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:
- account for all possible inputs;
- allow comparing algorithms without computing exact times;
- work from a high-level specification (pseudocode).
Approach:
- Worst-case analysis as a function of the instance size (requirements 1 and 2). Other options: average-case and probabilistic analysis.
- Counting elementary steps in the RAM model (requirements 2 and 3): assignments, arithmetic and logical operations are atomic. See Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation →.
- Asymptotic analysis to simplify counting: only the growth trend matters.
Worst-case time complexity
Let solve . Let be the number of operations of on instance . The worst-case time complexity is
the maximum number of operations on an instance of size ("operations" = elementary RAM steps). More precisely is a function of whichever parameter(s) describe the size.
Why exact is not needed
Computing it is often very hard, if not impossible: it is hard to find the worst instance of size 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 with (upper) and (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 of size :
- : upper bound, for every (so also bounds from above);
- : lower bound valid for every instance, for all (the algorithm systematically takes at least this many operations);
- : lower bound for at least one instance, (sometimes the algorithm takes at least this many).
Both and are lower bounds on the worst case .
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 currMaxSize: . For any instance of size :
- outside the loop a constant number of operations (constant with respect to );
- the loop makes iterations, each with a constant number of operations (the
ifmay cost more or less depending on whether the condition is true, but the cost is bounded by a constant).
So there are constants such that for every :
- bound the cost per iteration from above and below; bound the cost outside the loop.
- The loop is proportional to , approximated with .
- "Constant" means independent of the input size, not small (it can be ).
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 () and non-dominant additive terms (). Here upper and lower bound coincide: is proportional to , i.e. linear.
Asymptotic notation
Let map to non-negative reals. The notations express asymptotic bounds; the orders of growth () are the reference functions .
| Notation | Meaning |
|---|---|
| big-oh | upper bound |
| big-omega | lower bound |
| big-theta | tight bound |
| little-oh | strict upper bound |
Big-O
From on, grows no faster than .
How to prove it (example , ):
- Take = dominant term: .
- Rewrite the constant as a multiple of the dominant term: .
- Find when the inequality holds: for , so .
Hence with , . Other choices work too (e.g. , ). Also , but the tightest bound () is preferred.
| 7 | 1 | ||
| 3 | 1 | ||
| 1 | |||
| () | 1 |
Big-Omega
For : drop the positive constant, , so , and .
| 3 | 1 | ||
| 2 | 1 | ||
| 1 | 1 | ||
| 1 |
Big-Theta
i.e. : for all . So , , , .
Little-o
Big-O needs some constant , little-o needs every , however small: it is a stronger statement. Here usually depends on .
Examples: (since ); for .
Properties of growth rates
- Polynomials. If with , , then . Example: (expanding gives a polynomial of degree 5 with positive leading coefficient).
- Logarithms. For constants , , because and is a constant. So the base is omitted inside asymptotic notation; outside it, the base is assumed to be 2.
- Exponential vs polynomial. for constants , . Exponential time is always worse than polynomial time.
- Polylogarithmic vs polynomial. for constants , .
Typical growth rates
| Class | Notation |
|---|---|
| logarithmic | |
| polylogarithmic | , |
| linear | |
| polynomial | , (quadratic , cubic , ...) |
| exponential | , |
Remark: for exponentials we write because the exact growth depends on the base ().
Mathematical tools
- Floor : largest integer (integer part). , .
- Ceiling : smallest integer . , .
- Modulo (, ): remainder of the integer division,
%in Java. , . - Summations: Gauss' formula (proved 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 →) and the geometric series (with constant ).
Complexity analysis in practice
To prove : show that for all sufficiently large and every instance of size , for some constant . The algorithm performs at most operations.
- The proof must hold for all instances, with no assumption on a particular one.
- "Sufficiently large" means ; need not be computed.
- need not be computed; it suffices to prove it exists.
To prove :
- v.1: for all sufficiently large there exists at least one instance of size with (this is );
- v.2: for every instance of size the algorithm performs operations (this is ).
- For v.1 the proof must exhibit (the existence of) one such instance.
To get : prove both and .
Guidelines: 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: .
Example: prefixAverages
Given , compute with
i.e. is the mean of the first 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 AInefficient: every iteration recomputes partial sums from scratch. Cost: outer loop iterations, inner loop iterations with operations each, plus work per outer iteration:
(Gauss' formula). True for every instance, so the bound is tight: .
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 AThe loop runs times with a constant number of operations (independent of ) for every instance: . 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: for even, for odd
receives an array of integers and performs operations for each even integer and for each odd integer (). Size: . Note for all . Intuition: even elements cost .
Upper bound (every instance):
so .
Lower bound, v.2 (every instance):
so . Valid for all instances but not tight: instances with only odd numbers cost just .
Lower bound, v.1 (one instance): the instance with even elements costs , so .
Tight bound: and give .
Comparing algorithms and efficiency
For algorithms solving the same problem : if , then is asymptotically more efficient than ( 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: , counted in RAM elementary steps. Exact value is hard and unnecessary, so use bounds: (all instances), (all instances, lower), (at least one instance, lower).
- Definitions (, ):
- : (upper);
- : (lower);
- : both (tight);
- : for every (strict), equivalently .
- Proving : , . Proving : . Prefer the tightest, simplest (no constants or lower-order terms).
- Properties: polynomial of degree is ; (base omitted, default 2); ; .
- Classes: , , , , exponential .
- Tools: floor, ceiling, mod, Gauss , geometric series.
- In practice: must hold for every instance; v.1 needs one bad instance, v.2 holds for all; = + .
- arrayMax: constant outside + iterations of constant cost, so .
- prefixAverages: v1 nested loops ; v2 running sum . Rule: store and reuse partial results.
- Exercise ( even, odd): by , for all instances, from the all-even instance, so .
- Typical mistakes: proving on one instance only; calling a loose the complexity; saying "constant" means small; confusing with ; keeping the log base inside .
- 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 →.