Time Complexity
Time Complexity
Data Structures
Analysis of Algorithms
What is the goal?
• Analyze time requirements - predict how
running time increases as the size of the
problem increases:
time = f(size)
Why is it useful?
• To compare different algorithms.
Defining “problem size”
• Typically, it is straightforward to identify the size of
a problem, e.g.:
– size of array
– size of stack, queue, list etc.
– vertices and edges in a graph
Algorithm 1 Algorithm 2
Cost Cost
arr[0] = 0; c1 for(i=0; i<N; i++) c2
arr[1] = 0; c1 arr[i] = 0; c1
arr[2] = 0; c1
...
arr[N-1] = 0; c1
----------- -------------
c1+c1+...+c1 = c1 x N (N+1) x c2 + N x c1 =
(c 2 + c1) x N + c2
How do we find f(n)? (cont.)
Cost
sum = 0; c1
for(i=0; i<N; i++) c2
for(j=0; j<N; j++) c2
sum += arr[i][j]; c3
------------
c1 + c2 x (N+1) + c2 x N x (N+1) + c3 x N x N
Comparing algorithms
Approximation:
Cost ~ cost_of_elephants
Understanding Rate of Growth
(cont’d)
n4 + 100n2 + 10n + 50
Approximation:
n4
• On a graph, as
Value of function →
you go to the fA(n)=30n+8
right, a faster
growing
function fB(n)=n2+1
eventually
becomes
Increasing n →
larger...
Rate of Growth ≡Asymptotic Analysis
*
formal definition in CS477/677
Asymptotic Notation
*
formal definition in CS477/677
Asymptotic Notation
*
formal definition in CS477/677
Big-O Notation - Examples
fA(n)=30n+8 is O(n)
fB(n)=n2+1 is O(n2)
n3 - n2 is O(n3)
1273 is O(1)
More on big-O
O(g(n)) is a set of functions f(n)
f(n) ϵ O(g(n)) if “f(n)≤cg(n)”
Big-O Notation - Examples
fA(n)=30n+8
fB(n)=n2+1
Increasing n →
Estimating running time
Algorithm 1 Algorithm 2
Cost Cost
arr[0] = 0; c1 for(i=0; i<N; i++) c2
arr[1] = 0; c1 arr[i] = 0; c1
arr[2] = 0; c1
...
arr[N-1] = 0; c1
----------- -------------
c1+c1+...+c1 = c1 x N (N+1) x c2 + N x c1 =
(c2 + c1) x N + c2
O(N)
Estimate running time (cont.)
Cost
sum = 0; c1
for(i=0; i<N; i++) c2
for(j=0; j<N; j++) c2
sum += arr[i][j]; c3
------------
c1 + c2 x (N+1) + c2 x N x (N+1) + c3 x N x N
O(N2)
Running time of various statements
while-loop for-loop
Examples
i = 0;
while (i<N) {
X=X+Y; // O(1)
result = mystery(X); // O(N), just an example...
i++; // O(1)
}
X = X+i;
else
O(1)
X=0;