CS-311 Design and Analysis of Algorithms
CS-311 Design and Analysis of Algorithms
Algorithms
Lecture 2
Analysis Example
MaxElement(A[0..n-1)
maxVal = A[0];
for(I = 1; I < n; I++)
if(A[I] > maxVal)
maxVal = A[I];
return maxVal
Analysis Example
• Check whether all the elements in a given array
are distinct.
UniqueElements(A[0..n-1])
for(I = 0; i<n-1; i++)
for(j = i+1; j<n; j++)
if(A[i] = A[j])
return false
return true
Analysis Example
Max-Subsequence-Sum(Array, N) //Where N is size of Array
1 10 5 1 6
n n j
• First Sum j
N
i
N ( N 1)
2
1
k i
j i 1 i 1
• Next Sum n
(n i 1)(n i 2)
when i = n, n-i+1
j i
j i 1
2
n
(n i 1)(n i 2)
i1 2
A Maximum Sub Sequence
Sum Problem
• Solve the summation
= c1n3 + c2n2 + c3n
= O(n3)
• If n = 1000, Time constant = 1msec
=> T 109/(24*1000*60*60 )
11 days
Greatest Common Devisor Problem
f(n)
Tt
1 n0 n
f(n) <= g(n) for all n >= n0 Or
f(n) <= cg(n) for all n >= n0 and c = 1
g(n) is an asymptotic upper bound on f(n).
f(n) = O(g(n)) iff there exist two positive constants c and n 0 such that
Algorithms Analysis Framework
Asymptotic Notations (Lower Bound)
f(n)
g(n)
n0 n
Algorithms Analysis Framework
Asymptotic Notations (Tight Bound)
Asymptotically Tight Bound: f(n) = (g(n)),
iff there exit positive constants c1 and c2 and n0 such that
c1 g(n) <= f(n) <= c2g(n) for all n >= n0
c2g(n)
f(n)
c1g(n)
n0 n
Algorithms Analysis Framework
Asymptotic Notations (Example)
Example: show that (1/2)n2 – 3n = (n2)
To do so we must determine positive constants c1, c2
and n0 such that c1n2 <= (1/2)n2 – 3n <= c2n2, n >=
n0
Dividing by n2 c1 <= ½ - 3/n <= c2
Right Hand Inequality ½ <= c2 + 3/n
For positive n, if c2 >= ½ then the inequality holds.
Left Hand Inequality c1 + 3/n <= ½
For n = 7 and c1 <= 1/14, the inequality holds.
c1 <= 1/14, c2 >= ½ and n = 7
Algorithms Analysis Framework
Asymptotic Notations (Rules)
1. If T1(n) = O(f(n)) and T2(n) = O(g(n))
Then T1(n) + T2(n) = Max(O(f(n)), O(g(n)))
T1(n) * T2(n) = O(f(n) *g(n))
2. If T(x) is a polynomial of degree n, then
T(x) = (xn)
3. logk(n) = O(n) for any constant k. This tells
that logarithms grow very slowly.
4. Do not include any constants or low order
terms inside a big-Oh, e.g.,
T(n) = O(2n2) -------- wrong
T(n) = O(n2 + n) ----- wrong
Algorithms Analysis