COMP20007 Design of Algorithms
COMP20007 Design of Algorithms
COMP20007 Design of Algorithms
Analysis of Algorithms
Lars Kulik
Lecture 4
Semester 1, 2022
1
Establishing Growth Rate
In the last lecture we proved t(n) ∈ O(g (n)) for some cases of t
and g , using the definition of O directly:
t(n) t 0 (n)
lim = lim 0
n→∞ g (n) n→∞ g (n)
log2 n (log2 e) n1 1
lim √ = lim 1
= 2 log2 e lim √ = 0
n→∞ n n→∞ √
2 n
n→∞ n
3
Induction Trap (Polya)
4
Example: Finding the Largest Element in a List
5
Example: Selection Sort
(n − 2)(n − 1) n(n − 1)
= (n − 1)2 − = = Θ(n2 )
2 2
6
Example: Matrix Multiplication
function
MatrixMult(A[0..n − 1, 0..n − 1], B[0..n − 1, 0..n − 1])
for i ← 0 to n − 1 do
for j ← 0 to n − 1 do
C [i, j] ← 0.0
for k ← 0 to n − 1 do
C [i, j] ← C [i, j] + A[i, k] · B[k, j]
return C
.
7
Analysing Recursive Algorithms
M(0) = 0
M(n) = M(n − 1) + 1 for n > 0
To find a closed form, that is, one without recursion, we usually try
“telescoping”, or “backward substitutions” in the recursive part.
8
Telescoping
9
A Second Example: Binary Search in Sorted Array
10
Telescoping
log2 n ∈ O(ln n)
ln n ∈ O(log2 n)
Also note that since log nc = c · log n, we have, for all constants c,
log nc = O(log n)
12
Summarising Reasoning with Big-Oh
The third may be used with some nested loops. Suppose we have a
loop which is executed O(f (n)) times, and each execution takes
time O(g (n)). Then the execution of the loop takes time
O(f (n) · g (n)).
13
Some Useful Formulas
Pn
i=0 (2i + 1) = (n + 1)2
Pn
i=1 1/i = O(log n)
14
The Road Ahead
15