Lec 7
Lec 7
Running Time
80
with the input size.
Average case time is 60
often difficult to 40
determine. 20
algorithm 7000
Time (ms)
inputs of varying size 5000
and composition 4000
Use a method like 3000
System.currentTimeMillis() to 2000
get an accurate
1000
measure of the actual
running time 0
0 50 100
Plot the results I nput Size
An potentially
unbounded bank of 2
1
memory cells, each of 0
which can hold an
arbitrary number or
character
Memory cells are numbered and accessing
any cell in memory takes unit time.
Algorithm arrayMax(A, n)
currentMax A[0] 2
for i 1 to n 1 do 2n
if A[i] currentMax then 2(n 1)
currentMax A[i] 2(n 1)
{ increment counter i } 2(n 1)
return currentMax 1
Total 8n 2
© 2004 Goodrich, Tamassia Analysis of Algorithms 10
Estimating Running Time
Algorithm arrayMax executes 8n 2 primitive
operations in the worst case. Define:
a = Time taken by the fastest primitive operation
b = Time taken by the slowest primitive
operation
Let T(n) be worst-case time of arrayMax.
Then
a (8n 2) T(n) b(8n 2)
Hence, the running time T(n) is bounded by
two linear functions
© 2004 Goodrich, Tamassia Analysis of Algorithms 11
Growth Rate of Running
Time
Changing the hardware/ software
environment
Affects T(n) by a constant factor, but
Does not alter the growth rate of T(n)
The linear growth rate of the
running time T(n) is an intrinsic
property of algorithm arrayMax
3 log n + 5 is O(log n)
need c > 0 and n0 1 such that 3 log n + 5 c•log n for n
n0
© 2004 this is true
Goodrich, for
Tamassia c = 8 Analysis
and n0of= 2
Algorithms 17
Big-Oh and Growth Rate
The big-Oh notation gives an upper bound on the
growth rate of a function
The statement “f(n) is O(g(n))” means that the
growth rate of f(n) is no more than the growth rate
of g(n)
We can use the big-Oh notation to rank functions
according to their growth rate
f(n) is O(g(n)) g(n) is O(f(n))
g(n) grows Yes No
more
f(n) grows more No Yes
Same growth Yes Yes
© 2004 Goodrich, Tamassia Analysis of Algorithms 18
Big-Oh Rules
Algorithm prefixAverages1(X, n)
Input array X of n integers
Output array A of prefix averages of X #operations
A new array of n integers n
for i 0 to n 1 do n
s X[0] n
for j 1 to i do 1 2 … (n 1)
s s X[j] 1 2 … (n 1)
A[i] s (i 1) n
return A 1
big-Theta
f(n) is (g(n)) if there are constants c’ > 0