Complexity Analysis (Part II)
Complexity Analysis (Part II)
• Asymptotic Complexity
Definition of Big-O:
• Consider a function f(n) that is non-negative n 0. We say that
“f(n) is Big-O of g(n)” i.e., f(n) = O(g(n)), if n0 0 and a constant
c > 0 such that f(n) cg(n), n n0
Big-O (asymptotic) Notation
Implication of the definition:
• For all sufficiently large n, c *g(n) is an upper bound of
f(n)
Note: By the definition of Big-O:
f(n) = 3n + 4 is O(n)
it is also O(n2),
it is also O(n3),
...
it is also O(nn)
• However when Big-O notation is used, the function g in
the relationship f(n) is O(g(n)) is CHOOSEN TO BE AS
SMALL AS POSSIBLE.
– We call such a function g a tight asymptotic bound of f(n)
Big-O (asymptotic) Notation
Some Big-O complexity classes in order of magnitude from smallest to highest:
O(1) Constant
O(log(n)) Logarithmic
O(n) Linear
O(n log(n)) n log n
O(nx) {e.g., O(n2), O(n3), etc} Polynomial
To prove that f(n) is O(g(n)) we find any pair of values n0 and c that
satisfy:
f(n) ≤ c * g(n) for n n0
Note: The pair (n0, c) is not unique. If such a pair exists then there is
an infinite number of such pairs.
n0 1 2 3 4
c 8 4.25 3.55 3.3125 3
Proving Big-O Complexity
Example:
Prove that f(n) = 3n2 + 4n log n + 10 is O(n2) by finding appropriate
values for c and n0
We try to find some values of n and c by solving the following inequality
3n2 + 4n log n + 10 cn2
OR 3 + 4 log n / n+ 10/n2 c
i=1;
while (i < n) {
sum = sum + i; O(log n)
i = i*2
}
How to determine complexity of code structures
Nested Loops: Complexity of inner loop * complexity of outer loop.
Examples:
sum = 0
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) O(n2)
sum += i * j ;
i = 1;
while(i <= n) {
j = 1;
while(j <= n){
statements of constant complexity O(n log n)
j = j*2;
}
i = i+1;
}
How to determine complexity of code structures
Example:
for (int j = 0; j < n * n; j++)
sum = sum + j;
for (int k = 0; k < n; k++)
sum = sum - l;
System.out.print("sum is now ” + sum);