Analysis of Algorithms: CS 302 - Data Structures Section 2.6
Analysis of Algorithms: CS 302 - Data Structures Section 2.6
Analysis of Algorithms: CS 302 - Data Structures Section 2.6
2.) Then, count how many steps are used for an input
of that size:
- A step is an elementary operation such as
+, <, =, A[i]
N = 10 => 53 steps
N = 100 => 503 steps
N = 1,000 => 5003 steps
N = 1,000,000 => 5,000,003 steps
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
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
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
• Given two algorithms having running times
f(n) and g(n), how do we decide which one
is faster?
Approximation:
Cost ~ cost_of_elephants
Understanding Rate of Growth
(cont’d)
n4 + 100n2 + 10n + 50
Approximation:
n4
Value of function
fA(n)=30n+8
right, a faster
growing
function
fB(n)=n2+1
eventually
becomes
larger... Increasing n
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
n3 - n2 is O(n3) or O(n5)
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
O(Nx N2)x (N+1) + c3 x N x N
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)
}
• The body of the while loop: O(N)
• Loop is executed: N times
N x O(N) = O(N2)
Examples (cont.’d)
if (i<j)
O(N)
for ( i=0; i<N; i++ )
X = X+i;
else O(1)
X=0;