2 Complexity
2 Complexity
Note: Slides are written by Dr. Monica Nicolescu at University of Nevada, Reno
Algorithm Analysis
• The amount of resources used by the algorithm
– Space
– Computational time
• Running time:
– The number of primitive operations (steps) executed
before termination
• Order of growth
– The leading term of a formula
– Expresses the behavior of a function toward infinity
2
Asymptotic Notations
• A way to describe behavior of functions in the limit
3
Logarithms
• In algorithm analysis we often use the notation “log n”
without specifying the base
a logb x = x logb a 4
Asymptotic Notations - Examples
• For each of the following pairs of functions, either f(n) is
O(g(n)), f(n) is Ω(g(n)), or f(n) is Θ(g(n)). Determine
which relationship is correct.
– f(n) = log n2; g(n) = log n + 5 f(n) = Θ (g(n))
– f(n) = n; g(n) = log n2 f(n) = Ω(g(n))
– f(n) = log log n; g(n) = log n f(n) = O(g(n))
– f(n) = n; g(n) = log2 n f(n) = Ω(g(n))
– f(n) = n log n + n; g(n) = log n f(n) = Ω(g(n))
– f(n) = 10; g(n) = log 10 f(n) = Θ(g(n))
– f(n) = 2n; g(n) = 10n2 f(n) = Ω(g(n))
– f(n) = 2n; g(n) = 3n f(n) = O(g(n))
5
Asymptotic notations
• O-notation
6
Examples
– 1000n2+1000n = O(n2):
7
Asymptotic notations (cont.)
• Ω - notation
8
Examples
– 5n2 = Ω(n)
∃ c, n0 such that: 0 ≤ cn ≤ 5n2 ⇒ cn ≤ 5n2 ⇒ c = 1 and n0 = 1
– 100n + 5 ≠ Ω(n2)
∃ c, n0 such that: 0 ≤ cn2 ≤ 100n + 5
100n + 5 ≤ 100n + 5n (∀ n ≥ 1) = 105n
cn2 ≤ 105n ⇒ n(cn – 105) ≤ 0
Since n is positive ⇒ cn – 105 ≤ 0 ⇒ n ≤ 105/c
⇒ contradiction: n cannot be smaller than a constant
– n = Ω(2n), n3 = Ω(n2), n = Ω(logn)
9
Asymptotic notations (cont.)
• Θ-notation
10
Examples
– n2/2 –n/2 = Θ(n2)
• ½ n2 - ½ n ≤ ½ n2 ∀n ≥ 0 ⇒ c2= ½
• ½ n2 - ½ n ≥ ½ n2 - ½ n * ½ n ( ∀n ≥ 2 ) = ¼ n2
⇒ c1= ¼
– n ≠ Θ(n2): c1 n2 ≤ n ≤ c2 n2
11
Examples
– 6n3 ≠ Θ(n2): c1 n2 ≤ 6n3 ≤ c2 n2
⇒ c2 ≥ n/logn, ∀ n≥ n0 – impossible
12
More on Asymptotic Notations
• There is no unique set of values for n0 and c in proving the
asymptotic bounds
for all n ≥ 5
15
Some Simple Summation Formulas
n
n( n + 1)
• Arithmetic series: ∑ k = 1 + 2 + ... + n =
k =1 2
n
x n +1 − 1
• Geometric series: ∑
k =0
x = 1 + x + x + ... + x =
k 2 n
x −1
(x ≠ 1)
∞
1
– Special case: x < 1: ∑ =
x k
k =0 1− x
n
1 1 1
• Harmonic series: ∑
k =1 k
= 1 +
2
+ ... +
n
≈ ln n
n
• Other important formulas: ∑ lg k ≈ n lg n
k =1
n
1
∑ k p = 1p + 2 p + ... + n p ≈
k =1 p +1
n p +1
16
Mathematical Induction
• Used to prove a sequence of statements (S(1),
• Proof:
19
Readings
• Chapter 3
• Apendix A
20