Introduction to Algorithms M Tech
Introduction to Algorithms M Tech
UNIT-1
Algorithm Fundamentals
From:
Asif Khan
Department of CSE
GNIOT, Greater Noida
Reference:
Thomas H. Corman et al.
The MIT Press
Algorithms
What is an algorithm:
“ An algorithm is a set of steps or instructions to
solve any problem”
30
25
20
Y-Values
15
Column1
10 Column2
5
0
0 1 2 3 4
Time Complexity of an Algorithm
Example 1: Algorithm to find out the sum of an array of
length n.
Sum(A, n)
1. s= 0;
2. for ( i=1; i<=n; i++)
3. s= s+ A[i];
4. return (s);
Time Complexity of an Algorithm
Tabulation Method
s/e frequency steps
Sum(A, n)
s= 0; 1
for ( i=1;i<=n;i++) 1
s= s+ A[i] 1
return (s); 1
Time Complexity of an Algorithm
Tabulation Method
s/e frequency steps
Sum(A, n)
s= 0; 1 1
for ( i=1;i<=n;i++) 1 n+1
s= s+ A[i] 1 n
return (s); 1 1
Time Complexity of an Algorithm
Tabulation Method
s/e frequency steps
Sum(A, n)
s= 0; 1 1 1
for ( i=1;i<=n;i++) 1 n+1 n+1
s= s+ A[i] 1 n n
return (s); 1 1 1
Time Complexity of an Algorithm
Tabulation Method
s/e frequency steps
Sum(A, n)
s= 0; 1 1 1
for ( i=1;i<=n;i++) 1 n+1 n+1
s= s+ A[i] 1 n n
return (s); 1 1 1
Total Steps 2n+3
Time Complexity of an Algorithm
Time needed to execute the code t = k * (2n + 3)
where k is the time required to execute one statement
So t α (2n + 3)
as 3 is negligible for higher values of n
So t α 2n
So t α n
So T(n) = θ(n)
Time Complexity of an Algorithm
Example 2: Algorithm to find out factorial of n.
Fact( n )
1. if n= 0
2. return (1)
3. else
4. return n * Fact(n-1);
Time Complexity of an Algorithm
s/e frequency steps
Fact( n )
if n= 0 1
return (0); 1
else 0
return n * T(n-1) +1
Fact(n-1);
Time Complexity of an Algorithm
s/e frequency steps
n=0 n>0
Fact( n )
if n= 0 1 1 1
return (0); 1 1 0
else 0 - -
return n * T(n-1) +1 0 1
Fact(n-1);
Total
Steps
Time Complexity of an Algorithm
s/e frequency steps
n=0 n>0 n=0 n>0
Fact( n )
if n= 0 1 1 1 1 1
return (0); 1 1 0 1 0
else 0 - - 0 0
else 0 - - 0 0