RAM Model
RAM Model
Antonio Carzaniga
Faculty of Informatics
University of Lugano
Outline
Informal analysis of two Fibonacci algorithms
Measure of complexity
60
Ruby
Python
50 Scheme
C
Time (seconds)
40 C-wiz
Java
C-gcc
30 PythonSmart
20
10
0
0 20 40 60 80 100
n
© 2006–2007 Antonio Carzaniga 3
◮ Fibonacci is exponential in n
◮ in general
Fibonacci
Time SmartFibonacci
Input Size
In general we measure the complexity of an algorithm as a
function of the size of the input
◮ size measured in bits
◮ did we do that for SmartFibonacci?
Find(A, x)
1 for i ← 1 to length(A)
2 do if A[i] = x
3 then return true
4 return false
T (n) = Cn
© 2006–2007 Antonio Carzaniga 8
Worst-Case Complexity
In general we measure the complexity of an algorithm in the
worst case
FindEquals(A)
1 for i ← 1 to length(A) − 1
2 do for j ← i + 1 to length(A)
3 do if A[i] = A[j]
4 then return true
5 return false
n(n − 1)
T (n) = C
2
© 2006–2007 Antonio Carzaniga 9
Constant Factors
Does a load/store operation cost more than, say, an arithmetic
operation?
x ← 0 vs. y + z
T (n) = Θ(n2 )
Θ-Notation
Given a function g(n), we define the family of functions
Θ(g(n))
c2 g(n)
f (n)
c1 g(n)
n0
√ √
T (n) = n log n + n n ⇒ T (n) = Θ(n n)
n n
T (n) = 2 6 + n7 ⇒ T (n) = Θ(2 6 )
10+n 1
T (n) = n2
⇒ T (n) = Θ( n )
O-Notation
Given a function g(n), we define the family of functions
O(g(n))
cg(n)
f (n)
n0
√
T (n) = n log n + n n ⇒ T (n) = O(n2 )
n
T (n) = 2 6 + n7 ⇒ T (n) = O((1.5)n )
10+n
T (n) = n2
⇒ T (n) = O(1)
Examples
n2 − 10n + 100 = O(n log n)? NO
√
n = O(log2 n)? NO
n
n2 + (1.5)n = O(2 2 )? NO
FindEquals(A)
1 for i ← 1 to length(A) − 1
2 do for j ← i + 1 to length(A)
3 do if A[i] = A[j]
4 then return true
5 return false
T (n) = Θ(n2 )
◮ n = length(A)
◮ we measure the worst-case complexity
Ω-Notation
Given a function g(n), we define the family of functions
Ω(g(n))
f (n)
cg(n)
n0
f ≥g∧f ≤g⇔f =g
Examples
n2 + 4n − 1 = n2 + Θ(n)? YES
n2 + Ω(n) − 1 = O(n2 )? NO
n2 + O(n) − 1 = O(n2 )? YES
√ √
n log n + Θ( n) = O(n n)? YES
© 2006–2007 Antonio Carzaniga 20
o-Notation
The upper bound defined by the O-notation may or may not be
asymptotically tight
E.g.,
n log n = O(n2 ) is not asymptotically tight
n2 − n + 10 = O(n2 ) is asymptotically tight
ω-Notation
The lower bound defined by the Ω-notation may or may not be
asymptotically tight
E.g.,
2n = Ω(n log n) is not asymptotically tight
n + 4n log n = Ω(n log n) is asymptotically tight