Program Cost and Asymptotic Analysis
Program Cost and Asymptotic Analysis
Program Cost and Asymptotic Analysis
Part 1
Program Cost and Asymptotic Notation
Elias Koutsoupias
with thanks to Giulio Chiribella
fast computers
efficient algorithms.
j j
1 2 3 4 5 6 1 2 3 4 5 6
5 2 4 6 1 3 2 4 5 6 1 3
j j
1 2 3 4 5 6 1 2 3 4 5 6
2 5 4 6 1 3 1 2 4 5 6 3
j j
1 2 3 4 5 6 1 2 3 4 5 6 7
2 4 5 6 1 3 1 2 3 4 5 6
I NSERTION -S ORT(A)
Running time is
X
(cost of statement) · (number of time statement executed)
all statements
1 for j = 1 to A.length − 1
2 key = A[j + 1]
3 // Insert A[j + 1] into the sorted sequence A[1 . . j].
4 i = j
5 while i > 0 and A[i] > key
6 A[i + 1] = A[i]
7 i = i−1
8 A[i + 1] = key
where tj is the number of times the test of the while loop is executed for a
given value of j (note that tj may also depend on the input).
DAA 2020-21 1. Program cost and asymptotic notation – 18 / 33
Worst-case analysis
T (n) = c1 n + c2 (n − 1) + c4 (n − 1) + c5 ( n(n+1)
2
− 1)
+c6 ( n(n−1)
2
) + c 7
n(n−1)
2
+ c8 (n − 1)
= an2 + bn + c
T (n) = c1 n + c2 (n − 1) + c4 (n − 1) + c5 (n − 1) + c8 (n − 1)
= (c1 + c2 + c4 + c5 + c8 )n − (c2 + c4 + c5 + c8 )
O(g(n)) := { f : N −→ R+ : ∃n0 ∈ N+ . ∃c ∈ R+ . ∀n .
n ≥ n0 → f (n) ≤ c · g(n) }
O(g(n)) := { f : N −→ R+ : ∃n0 ∈ N+ . ∃c ∈ R+ . ∀n .
n ≥ n0 → f (n) ≤ c · g(n) }
by appealing to Lemma 1.
f (n) = O(g(n))
f (n) = O(g(n))
meaning that
f1 (n) = f2 (n) + h(n) ,
where h(n) is a generic function in O(g(n)).
When writing
f (n) = O(g(n))
we must bear in mind that it is a shorthand for f (n) ∈ O(g(n)).
Here “=” is not an equality between two objects.
In particular, it does not have the transitive property:
f (n) = O(g(n)) and h(n) = O(g(n)) does not imply f (n) = h(n)!
Two elements of the same set are not necessarily the same element!
Example
n = O(n3 ) and n2 = O(n3 ) but n 6= n2 .
f (n) = Ω(g(n))
to mean “there exist a positive integer n0 and a positive real c such that for
all n ≥ n0 , we have f (n) ≥ cg(n).”
If f ∈ Ω(g), then we say that “g is an asymptotic lower bound for f ”.
Example
1. nn = Ω(n!)
2. 2n = Ω(n10 ).
Exercise
Prove that f (n) = Ω(g(n)) iff g(n) = O(f (n)).
f (n) = Θ(g(n)) .
Equivalently, f = Θ(g) means that there exist positive reals c1 and c2 and
a positive integer n0 such that for all n ≥ n0 , we have
a = blogb a
logc a
logb a = logc b
1
logb a = loga b
alogb c = clogb a