7.1 O notation
Big O notation: a mathematical way of describing how a function generally behaves in relation to the input size
Rules:
Highest order term kept
Constants omitted
| Composite function | Big O notation |
|---|---|
| Notation | Name |
|---|---|
| Constant | |
| Logarithmic | |
| Linear | |
| Log-linear | |
| Quadratic | |
| Exponential |
7.2 Constant time operations
Constant time operation: an operation that always operates in the same amount of time for a given processor regardless of input values
Common constant time operations:
- Addition, subtraction, multiplication, and division of fixed size integer or floating point values
- Assignment of a reference, pointer, or other fixed size data value
- Comparison of two fixed size data values
- Read or write an array element at a particular index
Both hardware and programming language affect whether an operation is constant time
7.3 Algorithm analysis
Worst-case runtime: the runtime complexity for an input that results in the longest execution
int sum = 0;
for (int i = 0; i < N; i++) {
sum += i;
}| Stage | Operations | Count |
|---|---|---|
| Before loop | sum = 0, i = 0 | 2 |
| Within loop | i < N, i++, sum += i | 3N |
| After loop | Final comparison i < N | 1 |
| Total | 3 + 3N |
Operations before and after the loop execute a constant number of times, while operations within the loop execute N times
7.4 Growth of functions and complexity
| Notation | Meaning |
|---|---|
| Runtime function | |
| Comparison function | |
| Input size | |
| Threshold for asymptotic bounds |
Lower bound: a function that is the best case , for all values of
Upper bound: a function that is the best case , for all values of
An algorithm has infinitely many valid bounds, but we prefer the tightest asymptotic bounds that best describe its growth rate
Commonly used criteria used to choose a preferred upper or lower bound:
- A single-term polynomial
- Bounds as tightly as possible
An algorithm has infinitely many bounds. Preferred bounds are single-term polynomials that are as tight as possible and hold for all .
Ex.,
- Best case (lower bound): , for all .
- Worst case (upper bound): , for all .
Asympottic notation: the classification of runtime complexity that uses functions that indicate only the growth rate of the bounding function
| Notation | Bound | General form | Meaning |
|---|---|---|---|
| (big O notation) | Upper bound | A positive constant exists such that, for all , . | |
| (big Omega notation) | Lower bound | A positive constant exists such that, for all , . | |
| (big Theta notation) | Upper and lower bound | and . | |
| If no valid constants and threshold exist, the Big-O, Big-Ω, or Big-Θ claim is false. |