CS 253: Algorithms: Growth of Functions
CS 253: Algorithms: Growth of Functions
Chapter 3
Growth of Functions
In other words, how does the running time and space requirements change
as we increase the input size n ?
2
Types of Analysis
Worst case
◦ Provides an upper bound on running time
◦ An absolute guarantee that the algorithm would not run
longer, no matter what the inputs are
Best case
◦ Provides a lower bound on running time
◦ Input is the one for which the algorithm runs the fastest
Average case
◦ Provides a prediction about the running time
◦ Assumes that the input is random
3
Computing the Running Time
Measure the execution time ?
Not a good idea ! It varies for different
microprocessors!
4
Example
Algorithm X Cost
sum = 0; c1
for(i=0; i<N; i++) c2
for(j=0; j<N; j++) c3
sum += arrY[i][j]; c4
------------
5
Asymptotic Analysis
To compare two algorithms with running times f(n) and g(n), we need a
rough measure that characterizes how fast each function grows with
respect to n
In other words, we are interested in how they behave asymptotically (i.e. for
large n) (called rate of growth)
fB(n)
fB(n) = 3n2+5n +4 is order n2, or
O(n2). fA(n)
Function value
It is, at most, roughly proportional to
n2 .
Increasing n
7
More Examples …
n4 + 100n2 + 10n + 50 O(n4)
10n3 + 2n2 O(n3)
n3 - n2 O(n3)
constants
10 is O(1)
1273 is O(1)
what is the rate of growth for Algorithm X studied earlier (in Big O
notation)?
Function value
Youcan easily see that
30n+8 isn’t less than n
anywhere (n>0).
n
But it is less than
31n everywhere to
the right of n=8.
c = 31, n0 = 8
30n+8 O(n)
Big-O Visualization
O(g(n)) is the set of
functions with
smaller or same
order of growth as
g(n)
11
No Uniqueness
There is no unique set of values for n0 and c in proving
the asymptotic bounds
12
Definition of
n0=1
◦ 100n + 5 ≠ (n2)
-notation
15
Examples
◦ n2/2 –n/2 = (n2)
½ n2 - ½ n ≤ ½ n 2 n ≥ 0 c 2= ½
¼ n2 ≤ ½ n 2 - ½ n n ≥ 2 c 1= ¼
c2 ≥ n/logn, n≥ n0 – impossible
Relations Between Different Sets
RR
O( f ) ( f )
•f
( f )
17
Common orders of
magnitude
18
Common orders of magnitude
19
Logarithms and properties
In algorithm analysis we often use the
notation “log n” without specifying the base
f(n) = (g(n))
◦ f(n) = log n2; g(n) = log n + 5 f(n) = (g(n))
◦ f(n) = n; g(n) = log n2 f(n) = O(g(n))
◦ f(n) = log log n; g(n) = log n f(n) = (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) = O(g(n))
◦ f(n) = 2n; g(n) = 3n
Properties
Theorem:
f(n) = (g(n)) f = O(g(n)) and f = (g(n))
Transitivity:
◦ f(n) = (f(n))
◦ Same for O and
Symmetry:
22