This article is a part of Algorithm notebook by Fariz Mamad
Algorithm performance depends on the input size and the number of operations it executes. We, the software engineer, have to analyze the performance worst case according to time-space tradeoff.
O-Notation helps us analyze the worst case a.k.a. the upper bound of algorithm performance in terms of time complexity and space complexity.
Table of Contents
- Common O-Notation from worst to best
- O-Notation of time complexity from worst to best
- O-Notation of space complexity from worst to best
- Procedure to calculate complexity
1. Common O-Notation from worst to best
- Factorial — O(n!)
- Exponential — O(c^n)
- Polynomial — O(n^c)
- Superlinear — O(n log n)
- Linear — O(n)
- Logarithmic — O(log(n))
- Constant O(1)
1.1 Mathematic Examples
if n = 20:
1. Factorial -> 20! = 2.432902e+1
2. Exponential -> 220 = 1048576
3. Polynomial -> 202 = 400
4. Superlinear -> 20 log20 = 59.9
5. Linear -> 20 = 20
6. Logarithmic -> log20 = 2
7. Constant -> 1 = 1
2. O-Notation of time complexity from worst to best
- O(n!) — Factorial Algorithm : brute force algorithm for Traveling Salesman Problem
- O(c^n) — Exponential Algorithm : tower of hanoi
- O(n^c) — Polynomial Algorithm : bubble sort, selection sort, insertion sort, bucket sort
- O(n log n) — Superlinear Algorithm : heap sort, merge sort
- O(n) — Linear Algorithm : linear search
- O(log n) — Logarithmic Algorithm : binary search
- O(1) — Constant Algorithm : ideal
3. O-Notation of space complexity from worst to best
- O(n+k) — Sub-linear Algorithm : radix sort
- O(n) — Linear Algorithm : quick sort
- O(log n) — Logarithmic Algorithm : merge sort
- O(1) — Constant Algorithm : linear search, binary search, bubble sort, selection sort, insertion sort, heap sort, shell sort
4. Procedure to calculate complexity
- Figure out the input.
- Figure out n — input size / max. number of operations.
- Express the performance function of algorithm in terms of n
- Pay attention only to higher order terms of equation.
- Erase constant factor.
4.1 Procedure Example
- Constant Multiplication — if f(n) = c.g(n), then O(f(n)) = O(g(n))
- Polynomial Function — if f(n) = a_0 + a_1.n + a_2.n² + … + a_m.n^m, then O(f(n)) = O(nm)
- Logarithmic Function — if f(n) = log_a n and g(n) = log_b n, then O(f(n)) = O(g(n))
- Summation Function — if f(n) = f_1(n) + f_2(n) + … + f_m(n) and f_i(n) <= f_(i+1)(n) for all i = 1,2,…,m, then O(f(n)) = max(f_1(n), f_2(n), …, f_m(n))