| title |
|---|
Mathematical Foundations for Algorithm Analysis |
Definition: Function
Example: Order of growth, formally
$10n$ is$O(n^2)$
- Choose
$c=1$ and$n_0 = 10$ - For all
$n \ge 10$ :$10n \le 1 \times n^2$ - When
$n=10$ :$100 \le 100$ - When
$n=100$ :$1000 \le 1000$ , et cetera.
$5n+20$ is$O(n)$
- Choose
$c=25$ and$n_0 =1$ - For all
$n \ge 1$ :$5n + 20 \le 25n$ (constant 20 becomes negligible for large$n$ )
Layman's: "If
$A \le B$ and$B \le C$ , then$A \le C$ "
Layman's: When adding functions, only the fastest-growing one matters.
- e.g., If you have an algorithm that does
$O(n^2)$ work and then$O(n)$ work, the total is$O(n^2)$ because the smaller term gets absorbed.
Alternatively, instead of finding
Example: Comparing Orders of Growth
Q: Which functions grow faster?
$10n$ v.s.$n^2$ $n(n+1)/2$ v.s.$n^2$ A:
$n^2$ grows faster- They're the same speed
Some fundamental rules to remember.
All logarithmic functions belong to the same class
- e.g.,
$\log_2 n$ ,$\log_{10} n$ ,$\ln n$ are all$\Theta( \log n )$
Why?: Change of base formula. (
$\log_a n = \frac{ \log n }{ \log a}$ )
All polynomials of the same degree
Exponential functions
- e.g., $2^n$ vs $3^n$ are different growth rates (unlike logarithms)
You should know the fundamental ordering of complexity classes.
| Complexity | Name |
|---|---|
| constant | |
| logarithmic | |
| linear | |
|
|
|
| quadratic | |
| cubic | |
| exponential | |
| factorial |
Notation Reference:
$l$ : Lower bound$u$ : Upper bound$m$ : Middle point (for splitting sums)
For simple loops that run
- In particular,
$\sum_{1 \le i \le n} 1 = n - 1 + 1 = n \in \Theta(n)$
Example: Simple loop
for i <- 1 to n do something constant
For nested loops where inner loop depends on outer loop. $$ \sum_{1 \le i \le n} i = 1 + 2 + ... + n = n(n+1)/2 \approx n^2 / 2 \in \Theta(n^2) $$
Example: Nested loop with dependency
for i <- 1 to n for j <- 1 to i do something constant
For loops where the inner work grows quadratically with the outer variable. $$ \sum_{1 \le i \le n} i^2 = 1^2 + 2^2 + ... + n^2 = n(n+1)(2n+1)/6 \approx n^3 / 3 \in \Theta(n^3) $$
Example: Quadratic dependency
for i <- 1 to n for j <- 1 to i^2 do something constant
For algorithms that double/halve at each step. $$ \sum_{0 \le i \le n} a^i = 1 + a + ... + a^n = (a^{n+1} - 1) / (a - 1) \text{ for any } a \ne 1 $$
- In particular,
$\sum_{0 \le i \le n} 2^i = 2^0 + 2^1 + ... + 2^n = 2^{n+1} - 1 \in \Theta(2^n)$
Example: Exponentially growing work
operations <- 1 for i <- 1 to n do 'operations' amount of work operations <- operations * 2
Assorted properties for simplifying complex expressions. $$ \sum ( a_i \pm b_i ) = \sum a_i \pm \sum b_i $$ $$ \sum c a_i = c \sum a_i $$ $$ \sum_{l \le i \le u} a_i = \sum_{l \le i \le m} a_i + \sum_{m + 1 \le i \le u} a_i $$