Design and Analysis of Algorithms Lab Manual: Computer Science & Engineering Department NMAMIT, Nitte
Design and Analysis of Algorithms Lab Manual: Computer Science & Engineering Department NMAMIT, Nitte
LAB MANUAL
PART A
1. N- Queen’s Problems
The problem is to place n queens on a n-by-n chessboard so that no two queens attack each other
by being in the same row or in the same column or on the same diagonal.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<math.h>
void nqueen(int n)
{
int k=1; // queen 1 in row 1
if(a[k]<=n)
{
if(k==n) //if we reached last row then print solution
{
count++;
printf("Solution No %d:\n", count);
for(i=1;i<=n;i++)
{
printf("Queen No: %d is placed in Row No: %d and Column No %d\n",
i, i,a[i]);
}
}
else
{
k++;
a[k]=0;
}
}
else
{
k--; //backtrack to previous row
}
}
int main()
{
int n,noofsoln;
2. Dijkstra’s Algorithm
ALGORITHM Dijkstra(G,s)
//Dijkstra’s algorithm for single source shortest paths
//Input: A weighted connected graph G=<V,E> and its vertex s
//Output: The length dv of a shortest path from s to v
//and its penultimate vertex pv for every vertex v in V
PROGRAM
/* Dijkstra's algorithm to find Single Source Shortest Path in a graph*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int v1,v2, s;
int i,j,cost;
//clrscr();
printf("Enter no of vertices\n");
scanf("%d",&n);
printf("Enter no of edges\n");
scanf("%d",&e);
dijkstra(s);
printf("The Shortest Distance from %d to : \n",s);
for(i=1;i<=n;i++)
{
printf("%d = %d\n",i,dist[i]);
}
getch();
}
3. Kruskal’s Algorithm
ALGORITHM Kruskal(G)
//Kruskal’s algorithm for construction 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
PROGRAM
}
}
int Kruskals()
{
int i,j,ecounter=0;
int v1, v2;
int cost;
int total_cost=0;
while(ecounter<(n-1))
{
FindMin(&v1, &v2);
cost=A[v1][v2];
A[v1][v2]=A[v2][v1]=0;
if(root[v1]!=root[v2])
{
B[v1][v2]=B[v2][v1]=cost;
update(v1, v2);
total_cost=total_cost+cost;
ecounter++;
}
}
return total_cost;
}
int main()
{
int v1,v2;
int i,j,cost;
//clrscr();
printf("Enter no of vertices\n");
scanf("%d",&n);
printf("Enter no of edges\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
root[i]=i;
}
cost=Kruskals();
ALGORITHM Prim(G)
//Prim’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
VT ← {v0} // The set of tree vertices can be initialized with any vertex
ET ← Φ
for i ← 1 to |V| -1 do
find a minimum-weight edge e*=(v*,u*) among all the edges (u,v)
such that v is in VT and u is in V-VT
VT ← VT U {u*}
ET ← ET U{e*}
return ET
PROGRAM
/*Prim's algorithm to find minimum spanning tree*/
#include<stdio.h>
#include<conio.h>
int Prims()
{
int i,j;
int v1, v2;
int cost;
int total_cost=0;
for(i=1;i<n;i++)
{
FindMin(&v1, &v2);
cost=A[v1][v2];
B[v1][v2]=B[v2][v1]=cost;
visited[v1]=visited[v2]=1;
total_cost=total_cost+cost;
}
return total_cost;
}
int main()
{
int v1,v2;
int i,j,cost;
//clrscr();
printf("Enter no of vertices\n");
scanf("%d",&n);
printf("Enter no of edges\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
visited[i]=0;
}
visited[1]=1;
cost=Prims();
printf("The The minimum spanning tree for the given graph is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",B[i][j]);
printf("\n");
}
printf("\nThe total cost is: %d",cost);
getch();
}
ALGORITHM MFKnapsack(i,j)
//Implements the memory function method for the knapsack problem
//Input: A nonnegative integer i indicating the number of first
//items being considered and a nonnegative integer j indicating the knapsack’s capacity
//Output: The value of an optimal feasible subset of the first i items
//Note: Uses as global variables input arrays Weights[1..n],Values[1..n]
//and table V[0..n,0..W] whose entries are initialized with -1’s except for
//row 0 and column 0 initilized wit 0’s
if V[i,j] < 0
if j<Weights[i]
value ← MFKanpsack(i-1,j)
else
value ← max(MFKnapsack(i-1,j),Values[i]+MFKnapsack(i-1,j-Weights[i]))
V[i,j] ← value
return V[i,j]
PROGRAM
V[i][j]=value;
}
return V[i][j];
}
int main()
{
int i,j,val;
//clrscr();
printf("Enter no of items\n");
scanf("%d",&n);
val=MFKnapsack(n,W);
int Knapsack()
{
int i,j;
for(i=1;i<=n;i++)
{
for (j=1;j<=W;j++)
{
if(j-Weights[i]<0)
{
V[i][j]=V[i-1][j];
}
else
{
V[i][j]=max(V[i-1][j],Values[i]+V[i-1][j-Weights[i]]);
}
}
}
return V[n][W];
}
int main()
{
int i,j,val;
// clrscr();
printf("Enter no of items\n");
scanf("%d",&n);
val=Knapsack();
printf("The Knapsack table %d\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
printf("%d\t",V[i][j]);
}
printf("\n");
}
ALGORITHM HeapBottomUp(H[1..n])
//Constructs a heap from the elements of a given array
//by the bottom-up algorithm
//Input: An array H[1..n] of orderable items
//Output: A heap H[1..n]
for i ← └n/2┘downto 1 do
k ← i; v ← H[k]
heap ← false
while not heap and 2*k≤n do
j ← 2*k
if j<n //there are two children
if H[j] < H[j+1] j ← j+1
if v≥H[j]
heap ← true
else H[k] ← H[j]; k ← j
H[k] ← v
#include<stdio.h>
#include<conio.h>
int n=0,h[20];
void heapifybottomup()
{
int i,k,v,heapify,j;
for(i=(n/2);i>=1;i--)
{
k=i;
v=h[k];
heapify=0;
while(heapify==0 && 2*k<=n)
{
j=2*k;
if(j<n) //if there are 2 children
{
if(h[j]<h[j+1]) //checking both children
j=j+1;
}
if(v>=h[j])
{
heapify=1;
}
else
{
h[k]=h[j];
k=j;
}
}
h[k]=v;
}
}
void insert_ele(int ele)
{
n++;
h[n]=ele;
}
void remove_ele()
{
int temp;
heapifybottomup();
temp=h[1];
h[1]=h[n];
h[n]=temp;
printf("Deleted element is %d",h[n]);
n--;
}
void display()
{
int i;
if (n == 0)
printf("Queue is empty \n");
else
{
printf("\n The queue is : \n");
for(i=1;i<=n;i++)
{
printf("%d\t",h[i]);
}
}
int main()
{
int i,ele,choice;
while (1)
{
printf("\n1.Insert element to queue \n");
printf("\n2.Delete element from queue \n");
printf("\n3.Display all elements of queue \n");
printf("\n4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\n Enter the element : ");
scanf("%d",&ele);
insert_ele(ele);
break;
case 2:
remove_ele();
break;
case 3:
display();
break;
case 4:
exit(1);
}
}
getch();
return 0;
}
8. Heapsort
Heapsort Technique
1. (Heap construction): Construct a heap for a given array.
2. (Maximum deletions): Apply the root –deletion operation n – 1 times to the remaining
heap.
PROGRAM
#include<stdio.h>
#include<conio.h>
}
void heapsort(int h[],int n)
{
int i,temp,j;
for(i=n;i>1;i--)
{
heapifybottomup(h,i);
temp=h[1];
h[1]=h[i];
h[i]=temp;
}
}
int main()
{
int i,n,h[20];
// clrscr();
printf("\n Enter the number of elements : ");
scanf("%d",&n);
printf("\n Enter the elements : ");
for(i=1;i<=n;i++)
scanf("%d",&h[i]);
printf("\n The Entered array: ");
for(i=1;i<=n;i++)
{
printf("%d\t",h[i]);
}
heapsort(h,n);
9. Mergesort
ALGORITHM Mergesort(A[0..n-1])
//Sorts array A[0..n-1] by recursive mergesort
//Input:An array A[0..n-1] of orderable elements
//Output:Array A[0..n-1] sorted in nondecreasing order
if n>1
copy A[0..└n/2┘-1] to B[0..└n/2┘-1]
copy A[└n/2┘..n-1] to C[0..┌n/2┐-1]
Mergesort(B[0.. └n/2┘-1])
Mergesort(C[0.. ┌n/2┐-1)
Merge(B,C,A)
ALGORITHM Merge(B[0..p-1],C[0..q-1],A[0..p+q-1])
//Merges two sorted arrays into one sorted array
//Input:Arrays B[0..p-1] and C[0..q-1] both sorted
//Output:Sorted array A[0..p+q-1] of the elements of B and C
i ← 0; j ← 0; k ← 0
while i<p and j<q do
if B[i] ≤ C[j]
A[k] ← B[i]; i ← i+1
else A[k] ← C[j]; j ← j+1
k ← k+1
if i=p
copy C[j..q-1] to A[k..p+q-1]
else copy B[i..p-1] to A[k..p+q-1]
PROGRAM
#include<stdio.h>
#include<conio.h>
void MergeSort(int [], int);
void Merge(int [],int, int [],int, int []);
while(i<p)
{
a[k]=b[i];
i++;
k++;
}
while(j<q)
{
a[k]=c[j];
j++;
k++;
}
}
void MergeSort(int a[], int n)
{
int i,j,k,p,q;
int b[10],c[10];
if(n>1)
{
for(i=0;i<n/2;i++)
{
b[i]=a[i];
}
p=i;
for(i=n/2,j=0;i<n;i++,j++)
{
c[j]=a[i];
}
q=j;
MergeSort(b,p);
MergeSort(c,q);
Merge(b,p,c,q,a);
}
}
void main()
{
int i,a[20],n;
clrscr();
printf("Enter no of elements\n");
scanf("%d",&n);
MergeSort(a,n);
10. Quicksort
ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r
//Output: The subarray A[l..r] sorted in nondecreasing order
if l<r
s ← Partition (A[l..r]) //s is the split position
Quicksort(A[l....s-1])
Quicksort(A[s+1..r])
ALGORITHM Partition(A[l..r])
//Partitions a subarray by using its first element as pivot
//Input: A subarray A[l..r] of A[0..n-1], defined by its left and right indices l and r (l<r)
//Output: A partition of A[l..r], with split position returned as this function’s value
p ← A[l]
i ← l; j ← r+1
repeat
repeat i ← i+1 until A[i]≥ p
repeat j ← j-1 until A[j] ≤p
swap(A[i],A[j])
until i≥j
swap(A[i],A[j]) //undo last swap when i≥j
swap(A[l],A[j])
return j
PROGRAM
#include<stdio.h>
#include<conio.h>
int a[20];
void QuickSort(int, int);
int partition(int, int);
do
{
j--;
}while(a[j]>p);
temp=a[i];
a[i]=a[j];
a[j]=temp;
}while(i<=j);
temp=a[i]; /* undo last swap*/
a[i]=a[j];
a[j]=temp;
return j;
}
void QuickSort(int l, int r)
{
int s;
if(l<r)
{
s=partition(l,r);
QuickSort(l,s-1);
QuickSort(s+1,r);
}
}
void main()
{
int i,n;
clrscr();
printf("Enter no of elements\n");
scanf("%d",&n);
QuickSort(0,n-1);
In a digraph if we can list its vertices in such an order that ,for every edge in the graph, the vertex
where the edge starts is listed before the vertex where the edge ends then, such a problem is
called Topological Sorting
Write a C/C++ program to implement DFS based Topological Sorting algorithm for a given
digraph.
PROGRAM
#include<stdio.h>
#include<conio.h>
int A[20][20],visited[20],count=0,n,order[10],x=0;
void dfs(int v)
int w;
count=count+1;
visited[v]=count;
dfs(w);
order[x]=v;
x++;
int main()
int i,j,k,v1,v2,e;
// clrscr();
scanf("%d",&n);
scanf("%d",&e);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
A[i][j]=0;
for(i=1;i<=e;i++)
scanf("%d %d",&v1,&v2);
A[v1][v2]=1;
for(i=1;i<=n;i++)
visited[i]=0;
for(k=1;k<=n;k++)
{
if(visited[k]==0)
dfs(k);
for(i=n-1;i>=0;i--)
printf("%d\t",order[i]);
getch();
return 0;
12. Write a C/C++ program to implement Topological Sorting algorithm for a given digraph
using source removal technique.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int order[10],A[10][10],n,in[10],visited[10],e,k=0;
int is_all_nodes_visited()
{
int i;
for(i=1;i<=n;i++)
{
if (visited[i]==0)
return 0;
}
return 1;
}
int main()
{
int i,j,v1,v2,w;;
printf("Enter no of nodes\n");
scanf("%d",&n);
printf("Enter the number of edges of the graph:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
A[i][j]=0;
}
}
for(i=1;i<=n;i++)
{
in[i]=0;
}
for(i=1;i<=n;i++)
{
visited[i]=0;
}
A[v1][v2]=1;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(A[i][j]==1)
in[j]=in[j]+1;
}
}
while(1)
{
if(is_all_nodes_visited())
break;
else
for(i=1;i<=n;i++)
{
if(in[i]==0 && visited[i]==0)
{
order[k]=i;
k++;
visited[i]=1;
//printf("%d is visited \n",i);
for(w=1;w<=n;w++)
{
if(A[i][w]==1 && visited[w]==0)
{
in[w]--;
}
}
}
}
//getch();
return 0;
}
OR
#include <stdio.h>
#include <stdlib.h>
int n,e, in[30], A[30][30],k,order[30],visited[30];
void topo()
{
int i,w;
k=0;
for(i=1;i<=n;i++)
{
if(in[i]==0 && visited[i]==0)
{
order[k]=i;
k++;
visited[i]=1;
for(w=1;w<=n;w++)
{
if(A[i][w]==1 && visited[w]==0)
{
in[w]--;
}
}
i=0;
}
}
}
int main()
{
int i,j,v1,v2;
printf("Enter the the no. of vertices\n");
scanf("%d",&n);
printf("enter the number of edges\n");
scanf("%d",&e);
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
{
A[i][j]=0;
}
printf("enter edges one by one\n");
for(i=1;i<=e;i++)
{
scanf("%d%d",&v1,&v2);
A[v1][v2]=1;
}
for(i=1;i<=n;i++)
{
in[i]=0;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(A[i][j]==1)
{
in[j]=in[j]+1;
}
}
}
topo();
if(k==n)
{
printf("Topological order is\n");
for(i=0;i<n;i++)
{
printf("%d\n",order[i]);
}
}
else
{
printf("The graph is cyclic graph Topological Sort not possible\n");
}
return 0;
}
In time and space tradeoffs technique if time is at premium, we can precompute the function’s
values and store then in a table. In somewhat more general terms , the idea is to preprocess the
problem’s input, in whole or in part, and store the additional information obtained to accelerate
solving the problem afterward. We call this approach input enhancement.
Horspool’s Algorithm
ALGORITHM ShiftTable(P[0..m-1])
//Fills the shift table used by Horspool’s algorithm
//Input: Pattern P[0..m-1] and alphabet of possible characters
//Output: Table[0..size-1] indexed by the alphabet’s characters and filled with shift sizes the
given formula
T(c) =
the distance from the rightmost c among the first m-1 characters
of the pattern to its last character ,otherwise
ALGORITHM HorspoollMatching(P[0..m-1],T[0..n-1])
//Implements Horspool’s algorithm for string matching
//Input: Pattern P[0..m-1] and Text T[0..n-1]
//Output: The index of the left end of the first matching substring
//or -1 if there are no matches
ShiftTable(P[0..m-1]) // generate Table of shifts
i ← m-1
while i≤n-1 do
k← 0
while k≤m-1 and P[m-1-k]=T[i-k] do
k ← k+1
if k=m
return i-m+1
else i ← i+Table[T[i]]
return -1
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
char p[50],t[50];
int table[256];
int m,n;
void shifttable()
{
int i,j,temp;
for(i=0;i<256;i++)
{
table[i]=m;
}
for(j=0;j<m-1;j++)
{
temp=p[j];
table[temp]=m-1-j;
}
}
int horspool()
{
int i,k;
int temp;
shifttable();
i=m-1;
while(i<=n-1)
{
k=0;
while((k<=m) && (p[m-1-k]==t[i-k]))
k++;
if(k==m)
return (i-m+1);
else
temp=t[i];
i+=table[temp];
}
return -1;
}
int main()
{
int r;
printf("Enter the text\n");
scanf("%s",t);
n=strlen(t);
printf("Enter the pattern\n");
scanf("%s",p);
m=strlen(p);
r=horspool();
if(r==-1)
printf("Pattern not found\n");
else
printf("Pattern found at position %d\n",r);
getch();
}
Write a C/C++ program to implement Subset Sum problem using Backtracking technique.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int n,x[20],w[20],count=0,d;
int i;
x[k]=1;
if(s+w[k]==d)
{
count++;
printf("\nSolution No %d:\n", count);
for(i=1;i<=k;i++)
{
if(x[i]==1)
printf("%d\t", w[i]);
}
}
else
if(s+w[k]+w[k+1]<=d)
{
subsetsum(s+w[k],k+1,r-w[k]);
}
if((s+(r-w[k]))>=d && (s+w[k+1])<=d)
{
x[k]=0;
subsetsum(s,k+1,r-w[k]);
}
}
int main()
{
int i,j,sum=0;
printf("Enter the number of elements\n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
x[i]=0;
}
printf("Enter the elements in ascending order\n");
for (i=1;i<=n;i++)
{
scanf("%d",&w[i]);
}
printf("Enter the sum\n");
scanf("%d",&d);
for (i=1;i<=n;i++)
{
sum=sum+w[i];
}
if(sum<d)
printf("No solution\n");
else
subsetsum(0,1,sum);
return 0;
}