Analysis of Algorithm
Analysis of Algorithm
Algorithm
1
1. a. Implement Factorial of a number.
2.
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n);
// show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}
2
c. linear search/sequential search
#include<stdio.h>
main()
{
int array[100], search, c, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for ( c = 0 ; c < number ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
for ( c = 0 ; c < number ; c++ )
{
if ( array[c] == search ) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if ( c == number )
printf("%d is not present in array.\n", search);
return 0;
}
3
Session 2
Recursive algorithms
a. Factorial of a number
b. finding GCD using Euclid’s method
c. tower of Hanoi
Algorithms
ALGORITHM Factorial of a number(n)
Step 1: Start
Step 2: Read number n
Step 3: : If n==1 then return 1
Step 4: Else
f=n*factorial(n-1)
Step 4: Print factorial f
Step 5: Stop
ALGORITHM euclids(m,n)
function gcd(a, b)
if b = 0
return a;
else
return gcd(b, a mod b);
ALGORITHM Towerofhanoi
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
a. Factorial of a number
#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
4
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}
#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int main()
{
int a = 98, b = 56;
printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
return 0;
}
c. Tower of Hanoi
#include <stdio.h>
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
5
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Session 3
6
Session 4
8
printf("%d\t",a[i]);
}
void qsort(int a[],int low,int high)
{
int j;
if(low<high)
{
j=partition(a,low,high);
qsort(a,low,j-1);
qsort(a,j+1,high);
}
}
Session 5
Dynamic programming
a. Binomial coefficient(nCr)
b. Warshal’s algorithm to find transitive closure
c. Floyds algorithm to solve all pair shortest path problem
d. knapsack
9
Algorithms
Algorithm Binomial(n, k)
for i ← 0 to n do // fill out the table row wise
for i = 0 to min(i, k) do
if j==0 or j==i then C[i, j] ← 1 // IC
else C[i, j] ← C[i-1, j-1] + C[i-1, j] // recursive relation
return C[n, k]
Algorithm Warshal’s
10
int min(int a, int b);
int binomialCoeff(int n, int k)
{
int C[n+1][k+1];
int i, j;
for (i = 0; i <= n; i++)
{
for (j = 0; j <= min(i, k); j++)
{
if (j == 0 || j == i)
C[i][j] = 1;
else
C[i][j] = C[i-1][j-1] + C[i-1][j];
}
}
return C[n][k];
}
int min(int a, int b)
{
return (a<b)? a: b;
}
int main()
{ int n,k;
printf("enter the values of n and k");
scanf("%d%d",&n,&k);
printf ("Value of C(%d, %d) is %d ", n, k,binomialCoeff(n, k) );
return 0;
}
Warshal’s Algorithm
#include<stdio.h>
int max(int,int);
void warshal(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=max(p[i][j],p[i][k] && p[k][j]);
}
int max(int a,int b)
{
if(a>b)
return(a);
else
return(b);
}
void main()
11
{
int p[10][10]={0},n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:");
scanf("%d",&e);
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge %d:",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
}
printf("n Matrix of input data: n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
warshal(p,n);
printf("\n Transitive closure: \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
}
Floyd’s algorithm
#include<stdio.h>
int min(int,int);
void floyds(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
12
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}
KNAPSACK(0/1)
#include<stdio.h>
int v[20][20],values[23],weight[45];
int max(int m,int n)
{
if(m>=n) return m;
else return n;
13
}
int knapsack(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j-weight[i]>=0)
{
value=max(knapsack(i-1,j),(values[i]+knapsack(i-1,j-weight[i])));
}
else
{
value=knapsack(i-1,j);
}
v[i][j]=value;
}
return v[i][j];
}
main()
{
int n,i,j,w,profit;
printf("enter the no of elem\n");
scanf("%d",&n);
printf("enter the capacity\n");
scanf("%d",&w);
printf("enter the weights\n");
for(i=1;i<=n;i++)
{
scanf("%d",&weight[i]);
}
printf("enter the profits\n");
for(i=1;i<=n;i++)
{
scanf("%d",&values[i]);
}
for(i=0;i<=n;i++)
for(j=0;j<=w;j++)
if(i==0||j==0) v[i][j]=0;
else v[i][j]=-1;
profit=knapsack(n,w);
printf("the value is %d\n",profit);
Session 6
Greedy Techniques
a. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm
b. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm
14
c. From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijikstra’s algorithm
Algorithms
ALGORITHM Kruskal(G) //Kruskal’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = (V, E )
//Output: ET , the set of edges composing a minimum spanning tree of G
sort E in nondecreasing order of the edge weights w(ei 1 ) ≤ . . . ≤ w(ei| E| )
ET ←NULL;
ecounter ←0 //initialize the set of tree edges and its size
k←0 //initialize the number of processed edges
while ecounter < | V| − 1 do
k← k + 1
if ET ∪ { eik} is acyclic
ET← ET ∪ { eik};
ecounter ← ecounter + 1
return ET.
ALGORITHM Dijkstra's
Let's call the node we are starting with an initial node. Let a distance of a node X be the
distance from the initial node to it. Our algorithm will assign some initial distance values
and will try to improve them step-by-step.
1. Assign to every node a distance value. Set it to zero for our initial node and to infinity
for all other nodes.
2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbours and calculate their distance
(from the initial node). For example, if current node (A) has distance of 6, and an edge
connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If
this distance is less than the previously recorded distance (infinity in the beginning, zero
for the initial node), overwrite the distance.
4. When we are done considering all neighbours of the current node, mark it as visited. A
visited node will not be checked ever again; its distance recorded now is final and
minimal.
5. Set the unvisited node with the smallest distance (from the initial node) as the next
"current node" and continue from step 3.
6. When all nodes are visited, algorithm ends.
Coding using C Language
15
a) Using Kruskal's Algorithm
#include<stdio.h>
int i,j,k,a,b,v,u,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
void main()
{
printf("\nEnter the number of vertices\n");
scanf("%d",&n);
printf("Enter the cost of matrix::\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
printf("\nThe edges of spanning treeare:\n\n");
while(ne<n)
{
for (i=1,min=999;i<=n;i++)
for (j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}}
while(parent[u]) u=parent[u];
while(parent[v]) v=parent[v];
if(u!=v)
{
printf("\n%d\tEdge(%d,%d)=%d",ne++,a,b,min);
mincost+=min;
parent[v]=u;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMiINCOST=%d\n",mincost);
16
scanf("%d",&n);
printf("The cost of matrix=\t");
for( i=1;i<=n;i++)
for( j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0) cost[i][j]=999;
}
if(visited[v]==0)
{
printf("\n%d\t Edge \t(%d, %d)=%d\n",ne++, a, b, min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\t mincost=%d\n",mincost);
DIJKSTRAS PROGRAM
#include<stdio.h>
main()
{
int visited[23],i,k,w,v,min;
int n,sv,j,dist[10],cost[10][10];
17
printf("\nenter the no of vertices");
scanf("%d",&n);
printf("enter the cost of matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
printf("enter the source\n");
scanf("%d",&sv);
for(i=1;i<=n;i++)
{
visited[i]=0;
dist[i]=cost[sv][i];
}
visited[sv]=1;
dist[sv]=1;
for(k=2;k<=n;k++)
{
min=999;
for(w=1;w<=n;w++)
if(dist[w]<min && visited[w]==0)
{
min=dist[w];
v=w;
}
visited[v]=1;
for(w=1;w<=n;w++)
if(dist[v]+cost[v][w]<dist[w])
dist[w]=cost[v][w]+dist[v];
}
printf("shortest path\n");
for(j=1;j<=n;j++)
{
if(j!=sv)
printf("%d->%d==%d\n",sv,j,dist[j]);
}
}
18
Session 7
Algorithm
AlGORITHM Backtrack(X[l..i])
//Gives a template of a generic backtracking algorithm
//Input: X[Li] specifies first i promising components of a solution
//Output: All the tuples representing the problem's solutions
#include<stdio.h>
#include<stdlib.h>
const int max=20;
int place(int x[],int k)
{
int i;
for(i=0;i<k;i++)
if (x[i]==x[k] || abs(x[i]-x[k])==abs(i-k))
return 0;
return 1;
for(i=0;i<n;i++)
{
19
for(j=0;j<n;j++)
printf("%c", chessb[i][j]);
printf ("\n");
}
printf ("\n");
void nqueens(int n)
{
int x[max];
int k;
x[0]=-1;
k=0;
while(k>=0)
{
x[k]=x[k]+1;
while(x[k]<n && !place(x,k))
x[k]=x[k]+1;
if(x[k]<n)
if (k==n-1)
display(x,n);
else
{
k++;
x[k]=-1;
}
else
k--;
}
}
main()
{
int n;
printf("enter the no of queens\n");
scanf("%d", &n);
printf("the soln to %d queens problem is \n", n);
nqueens(n);
}
20