COMP90038 Algorithms and Complexity
COMP90038 Algorithms and Complexity
Analysis of Algorithms
Michael Kirley
Lecture 4
Semester 1, 2017
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 ′ (n)
lim = lim ′
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
(n − 2)(n − 1) n(n − 1)
= (n − 1)2 − = = Θ(n2 )
2 2
Algorithms and Complexity (2017) Analysis of Algorithms 5 / 14
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
X n−1
n−1 X
n−1 X
M(n) = 1
i =0 j=0 k=0
✎
Algorithms and Complexity (2017) Analysis of Algorithms 6 / 14
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.
C (n) = C (n/2) + 1
= [C (n/4) + 1] + 1
= [[C (n/8) + 1] + 1] + 1
..
.
= [[. . . [[C (0) + 1] + 1] + · · · + 1] + 1]
| {z }
1+log2 n times
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)
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)).