Analysis of Algorithms
Measuring Algorithm Efficiency
Lecture Outline
What is an Algorithm?
Big-O notation
Example Analyses
Proof by induction
Their sums
Algorithm
Analysis of Algorithm
Counting Operations
i 1
i 1
j 1
100 ( 2)
Total Ops = A + B
n
Algorithm B is 0.39n3 + n
10
Asymptotic Analysis
11
Example
f(1000)
= 2(1000)2 + 100(1000)
= 2,000,000 + 100,000
f(100000)
= 2(100000)2 + 100(100000)
= 20,000,000,000 + 10,000,000
12
a(n) = n + 4
Leading term: n
13
14
15
Formal definition
Time
Algorithm A
f(n)
n0
[ CS1020E AY1617S1 Lecture 9 ]
Problem Size
16
Observations
Time
Algorithm A
f(n)
n0
[ CS1020E AY1617S1 Lecture 9 ]
Problem Size
17
Solution
Questions
18
Growth Terms
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?)
[ CS1020E AY1617S1 Lecture 9 ]
19
Independent of n
20
21
22
23
24
25
26
int sum = 0;
for (int i = 1; i <= n; i = i*3)
for (int j = 1; j <= i; j++)
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)
27
Prove it!
Hints: f(1)=1, f(n)=f(n-1) + 1 + f(n-1), and prove by
induction
28
29
Observation
30
Important characteristics
If x = m, found it!
If x > m, eliminate m and positions before m
If x < m, eliminate m and positions after m
31
32
33
O(f(n))
34
...
35
We have
n/2k = 1 2k = n k = log2(n) = lg(n)
Observation
36
Worst-Case Analysis
Best-Case Analysis
Average-Case Analysis
Hardest/impossible to analyze
37
Summary
Algorithm Definition
Algorithm Analysis
Counting operations
Asymptotic Analysis
Best-case
Worst-case
Average-case
38