L9 - Analysis of Algorithms PDF
L9 - Analysis of Algorithms PDF
Analysis of Algorithms
Analysis of Algorithm
To evaluate rigorously the resources (time and
space) needed by an algorithm and represent the
result of the evaluation with a formula
For this module, we focus more on time
requirement in our analysis
The time requirement of an algorithm is also called
the time complexity of the algorithm
[ CS1020E AY1617S1 Lecture 9 ]
4
Measure Actual Running Time?
We can measure the actual running time of a
program
Use wall clock time or insert timing code into
program
k*f(n)
Time
Algorithm A
f(n)
n0 Problem Size
[ CS1020E AY1617S1 Lecture 9 ]
16
The Big-O Notation
When problem size is larger than n0, Algorithm A is
bounded from above by k * f(n)
Observations
n0 and k are not unique
There are many possible f(n)
k*f(n)
Time
Algorithm A
f(n)
n0 Problem Size
[ CS1020E AY1617S1 Lecture 9 ]
17
Example: Finding n0 and k
Given complexity of Algorithm A is 2n2 + 100n
Claim: Algorithm A is of O(n2)
Solution
2n2 + 100n < 2n2 + n2 = 3n2 whenever n >100
Set the constants to be k = 3 and n0 = 100
By definition, we say Algorithm A is O(n2)
Questions
Can we say A is O(2n2) or O(3n2)?
Can we say A is O(n3)?
[ CS1020E AY1617S1 Lecture 9 ]
18
Growth Terms
In asymptotic analysis, a formula can be simplified
to a single term with coefficient 1 (how?)
Such a term is called a growth term (rate of
growth, order of growth, order of magnitude)
The most common growth terms can be ordered as
follows (note that many others are not shown)
O(1) < O(log n) < O(n) < O(n log n) < O(n2) < O(n3) < O(2n) < …
“fastest” “slowest”
“log” = log2
In big-O, log functions of different bases are all the same (why?)
int sum = 0;
for (int i = 1; i < n; i = i*2) {
sum++;
}
f(n) = 1 + 3 + 9 + 27 + … + 3(log3 n)
= 1 + 3 + … + n/9 + n/3 + n
= n + n/3 + n/9 + … + 3 + 1
= n * (1 + 1/3 + 1/9 + …)
≤ n * (3/2)
= 3n/2
= O(n)
[ CS1020E AY1617S1 Lecture 9 ]
27
Analysis 1: Tower of Hanoi
Number of moves made by the algorithm is 2n − 1
Prove it!
Hints: f(1)=1, f(n)=f(n-1) + 1 + f(n-1), and prove by
induction
if (x > a[mid])
return binarySearch(a, x, mid+1, high);
else if (x < a[mid])
return binarySearch(a, x, low, mid–1);
else
return mid; // Base Case 2: item found
}