Lecture 3 1
Lecture 3 1
Anna-Simone Frank1
MNF130
Spring 2024
1
Slides created by Tom Michoel and modified by Erik Maartensson and
Anna-Simone Frank
Algorithms
Given an algorithm that solves some problem in f (n) operations when the
problem size is n.
I How do we compare this algorithm against other algorithms solving
the same problem?
I How do we compare the algorithm against itself for other problem
sizes.
Asymptotic complexity
Given an algorithm that solves some problem in f (n) operations when the
problem size is n.
I How do we compare this algorithm against other algorithms solving
the same problem?
I How do we compare the algorithm against itself for other problem
sizes.
Given an algorithm that solves some problem in f (n) operations when the
problem size is n.
I How do we compare this algorithm against other algorithms solving
the same problem?
I How do we compare the algorithm against itself for other problem
sizes.
Example (2.)
If f1 (n) is O(n2 ) and f2 (n) is O(log(n)), then f1 (n) · f2 (n) is O(n2 log(n)).
Some basic rules for computing asymptotic complexity
Example (2.)
If f1 (n) is O(n2 ) and f2 (n) is O(log(n)), then f1 (n) · f2 (n) is O(n2 log(n)).
Example (3.)
A polynomial p(n) = ak nk + ak−1 nk−1 + · · · a1 n + a0 is O(nk ).
Some basic rules for computing asymptotic complexity
Example (2.)
If f1 (n) is O(n2 ) and f2 (n) is O(log(n)), then f1 (n) · f2 (n) is O(n2 log(n)).
Example (3.)
A polynomial p(n) = ak nk + ak−1 nk−1 + · · · a1 n + a0 is O(nk ).
fn = fn−1 + (n − 1)
n(n − 1)
fn =
2
Binary search
Searching for an element in a list can be done faster if the list is sorted.
4 12
2 6 10 14
1 3 5 7 9 11 13 15
We can write binary search as a recursive algorithm:
Algorithm (Binary search recursive)
procedure binary search(x integer, a1 , . . . , an : increasing integers)
if n = 0 (empty list) then
location := 0
return location
else if x = am then
location := m
return location
else if x > am then
binary search(x, am+1 , . . . , an )
else
binary search(x, a1 , . . . , am−1 )
if x = ai then
location := i
else
location := 0
return location
Binary search takes input of size n, and reduces the problem to a search
on input of size n/2, needing two comparisons to do so: one to determine
whether the midpoint is the searched for element, and one to determine
whether to proceed with the left or right half of the list.
Let f (n) be the number of comparison in binary search for input of size
n. Then
n
f (n) = f +2
2
Taking again n = 2k and writing ak = f (2k ), we get a recurrence relation
ak = ak−1 + 2
ak = a + dk
Plugging this into the recurrence relation and initial condition gives
a + dk = a + d(k − 1) + 2 a1 = a + d = 1
d =2 a = −1
Hence
f (2k ) = ak = 2k − 1
or