Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

DR.

AMBEDKAR INSTITUTE OF TECHNOLOGY


(An Autonomous Institute, Affiliated to Visvesvaraya Technological University, Belagavi, Accredited by NAAC, with ‘A’ Grade)
Near Jnana Bharathi Campus, Bengaluru – 560056

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

ALGORITHM DESIGN TECHNIQUES


LABORATORY MANUAL

SUBJECT: ALGORITHM DESIGN TECHNIQUES LAB


SUBJECT CODE: 18CSL47
ACADEMIC YEAR: 2019-2020
PREPARED BY: ASHA, SOMWYA C L
SYLLABUS

Sub Title: Algorithm Design Techniques Laboratory

Sub Code:18CSL47 No. of Credits:1= 0 :0 : 1 (L-T-P) No. of lecture


Exam Duration: 3 hours CIE + SEE = 50 + 50 =100 hours/week: 3
Course objectives:
1. To study about various designing paradigms of algorithms for solving problems
2. To analyze run time of algorithms and understand fundamental algorithmic problems
3. Make the students imbibe the art of writing elegant and efficient programs as well as debugging skills.
Design, develop and implement the specified algorithms for the following problems using C/C++
Language in LINUX / Windows environment.

1 Sort a given set of elements using Bubble Sort/Selection Sort and determine the time
required to sort the elements. Plot a graph of number of elements versus time taken. Specify
the time efficiency class of this algorithm. The elements can be read from a file or can be
generated using the random number generator.
2 Implement Merge Sort algorithm to sort a given set of elements and determine the time
required to sort the elements. Repeat the experiment for different values of n, the number of
elements in the list to be sorted and plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.
3 Sort a given set of elements using the Quicksort method and determine the time required to
sort the elements. Repeat the experiment for different values of n, the number of elements in
the list to be sorted and plot a graph of the time taken versus n.
The elements can be read from a file or can be generated using the random number generator.
4 From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm.
5 Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

6 Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

7 Obtain the Topological ordering of vertices in a given digraph.


8 a. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
b. Compute the transitive closure of a given directed graph using Warshall's algorithm.
9 Implement 0/1 Knapsack problem using Dynamic Programming.
10 Implement Traveling Salesperson problem using Dynamic programming.

11 Implement Horspool’s algorithm for String Matching using space & time tradeoff concept

12 Implement N Queen's problem using Back Tracking.

13 Find a subset of a given set S = {sl,s2,.....,sn} of n positive integers whose sum is equal to a
given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions
{1,2,6}and {1,8}. A suitable message is to be displayed if the given problem instance doesn't
have a solution.

2|Page Dept. of CSE, Dr. AIT


Note: In the examination each student picks one question from the lot of all 13 questions.

Course Statements Blooms


Outcomes Level
CO1 Design an algorithm using appropriate design techniques. 3
CO2 Apply and implement learned algorithm design techniques and data 3
structures to solve real world problems
CO3 Analyze and compare the performance of algorithms. 3

Course POs PSOs


Outco PO PO PO PO PO PO PO PO PO PO PO PO PS PS PSO
mes 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 3
CO1 2 3 3 3 - - - - - - - - 3 3 -
CO2 2 3 3 3 - - - - - - - - 3 3 -
CO3 2 3 2 2 - - - - - - - - 3 2 -

3|Page Dept. of CSE, Dr. AIT


TABLE OF CONTENT

PAGE
SL. NO PROGRAM
NO.

1.1 Bubble Sort 5-7


1
1.2 Selection Sort 7-9

2 Merge Sort 10-13

3 Quick Sort 14-17

4 Dijkstra’s Algorithm 18-20

5 Kruskal’s Algorithm 21-24

6 Prim’s Algorithm 25-28

7 Topological Ordering 29-32

8.1 Floyd’s Algorithm 33-35


8
8.2 Warshall’s Algorithm 36-38

9 0/1 Knapsack Problem 39-41

10 Travelling Salesman Problem 42-44

11 Horspool’s Algorithm 45-47

12 N Queen’s Problem 48-50

13 Sum Of Subset Problem 51-53

4|Page Dept. of CSE, Dr. AIT


1. Sort a given set of elements using Bubble Sort/Selection Sort and
determine the time required to sort the elements. Plot a graph of
number of elements versus time taken. Specify the time efficiency
class of this algorithm. The elements can be read from a file or can
be generated using the random number generator.

ALGORITHM BubbleSort(a,n)
//Purpose: To arrange the numbers in ascending order
//Input: n- The number of items in the array
a- Array of unsorted elements
//Output: a contains sorted elements

for j<-1 to n-1 do


for i<-0 to n-j-1 do
if a[i] > a[i+1] then
temp <- a[i]
a[i] <- a[i+1]
a[i+1] <- temp
end if
end for
end for

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<time.h>
void bubblesort(int a[10000],int n)
{
int i,j,temp;
for(j=1;j<n;j++)
{
for(i=0;i<n-j;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
}

5|Page Dept. of CSE, Dr. AIT


void main()
{
int n, a[10000],k;
clock_t st,et;
float ts;
clrscr();
printf("\n Enter Numbers of elements:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
bubblesort(a, n);
et=clock();
ts=et-st/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %f",ts);
getch();
}

OUTPUT
1)
Enter Number of elements:
10

The Random Numbers are:


4
20
16
24
5
18
38
75
10
2

The Sorted Numbers are:

6|Page Dept. of CSE, Dr. AIT


2
4
5
10
16
18
20
24
38
75
The time taken to sort 10 elements is 0.00

Time Complexity of Bubble Sort: O(n2)

ALGORITHM SelectionSort(a,n)
//Purpose: To arrange the numbers in ascending order
//Input: n- The number of items in the array
a- Array of unsorted elements
//Output: a contains sorted elements

for i<-0 to n-2 do


pos<- i
for j<-i+1 to n-1 do
if (a[j] < a[pos])
pos<-j
end for
temp <- a[pos]
a[pos] <- a[i]
a[i] <- temp
end for

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<time.h>
void selectionsort(int a[10000],int n)
{
int i,j,min,temp,pos;
for(j=0;j<n-1;j++)
{
pos=j;

7|Page Dept. of CSE, Dr. AIT


for(i=j+1;i<n;i++)
{
if(a[i]<a[pos])
{
pos=i;
}
}
temp=a[j];
a[j]=a[pos];
a[pos]=temp;
}
}

void main()
{
int n, a[10000],k;
clock_t st,et;
float ts;
clrscr();
printf("\n Enter How many Numbers:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
selectionsort(a, n);
et=clock();
ts=et-st/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %f",ts);
getch();
}

OUTPUT
1>
Enter Number of elements:
10

The Random Numbers are:

8|Page Dept. of CSE, Dr. AIT


4
20
16
24
5
18
38
75
10
2

The Sorted Numbers are:


2
4
5
10
16
18
20
24
38
75
The time taken to sort 10 elements is 0.00

Time Complexity of Selection Sort:O(n2)

9|Page Dept. of CSE, Dr. AIT


2. Implement Merge Sort algorithm to sort a given set of elements
and determine the time required to sort the elements. Repeat the
experiment for different values of n, the number of elements in the
list to be sorted and plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the
random number generator.

ALGORITHM mergesort(a,low,high)
//This algorithm 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 non-decreasing order
Begin
if(low>=high) return
mid<-(low+high)/2
mergesort(a,low,mid)
mergesort(a,mid+1,high)
simplemerge(a,low,mid,high)
End

ALGORITHM simplemerge(a,low,mid,high)
/*This algorithm merges the given list into 2 list till the list is totally sorted
recursively*/
//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.
Begin
i<-low
j<-mid+1
k<-low
while(i<=mid and j<=high)
do
if(a[i]<a[j])
then
c[k] <-- a[i]
i<-i+1
k<-k+1
else
c[k] <-- a[j]
j<-j+1
k<-k+1
endif-else

10 | P a g e Dept. of CSE, Dr. AIT


endwhile
while(i<=mid)
do
c[k] <-- a[i]
k<-k+1
i<-i+1
endwhile
while(j<=mid)
do
c[k] <-- a[j]
k<-k+1
j<-j+1
endwhile
for i<-low to high
do
a[i]<-c[i]
endfor
End

PROGRAM
# include <stdio.h>
# include <conio.h>
#include<time.h>
void Merge(int a[], int low, int mid, int high)
{
int i, j, k, b[10000];
i=low; j=mid+1; k=low;
while ( i<=mid && j<=high )
{
if( a[i] <= a[j] )
b[k++] = a[i++] ;
else
b[k++] = a[j++] ;
}
while (i<=mid)
b[k++] = a[i++] ;
while (j<=high)
b[k++] = a[j++] ;
for(k=low; k<=high; k++)
a[k] = b[k];
}

void MergeSort(int a[], int low, int high)


{

11 | P a g e Dept. of CSE, Dr. AIT


int mid;
if(low >= high)
return;
mid = (low+high)/2 ;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
delay(1);
}

void main()
{
int n, a[10000],k;
clock_t st,et;
float ts;
clrscr();
printf("\n Enter Numbers of elements:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
MergeSort(a, 1, n);
et=clock();
ts=et-st/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %f",ts);
getch();
}

OUTPUT
1)
Enter Number of elements:
10

The Random Numbers are:


4
-20416
10637

12 | P a g e Dept. of CSE, Dr. AIT


0
2004
512
1098
-20138
10775
10

The Sorted Numbers are:


-20146
-20138
0
4
10
512
1098
2004
10637
10775

The time taken to sort 10 elements is 0.00

2)
Enter the size of array
1000
The time taken to sort 1000 elements is 2.0329

Enter the size of array


2000
The time taken to sort 2000 elements is 4.0659

Enter the size of array


3000
The time taken to sort 3000 elements is 6.0989

Enter the size of array


4000
The time taken to sort 4000 elements is 8.1318

Time Complexity of Merge Sort: O(nlogn)

13 | P a g e Dept. of CSE, Dr. AIT


3. Sort a given set of elements using the Quick sort method and
determine the time required to sort the elements. Repeat the
experiment for different values of n, the number of elements in the
list to be sorted and plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the
random number generator.

ALGORITHM quicksort(a,low,high)
//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: Subarray A[l..r] sorted in nondecreasing order
Begin
if(low>high) return
k<-partition(a,low,high)
quicksort(a,low,k-1)
quicksort(a,k+1,high)
End

ALGORITHM partition(a,low,high)
/*This algorithm partitons the given list into 2 list till the list contains only 1 element
recursively*/
//Partition a subarray by using its first element as its 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 the split position returned as this function’s value

Begin
key<-a[low]
i<-low
j<-high+1
while(i<=j)
do i<-i+1 while(key>=a[i])
do j<-j-1 while(key<a[j])
if (i<j)
then
exchange(a[i],a[j])
endif
endwhile
exchange(a[low],a[j])
return j
End

14 | P a g e Dept. of CSE, Dr. AIT


PROGRAM
# include <stdio.h>
# include <conio.h>
# include <time.h>

int partition(int a[], int low, int high)


{
int i, j, key, temp;
key=a[low];
i=low;
j=high;
while(i<=j)
{
while ( a[i] <= key )
i=i+1;
while ( a[j] > key )
j=j-1;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}

void QuickSort(int a[],int low,int high)


{
int k;
if(low>=high)
return;
k=partition(a,low,high);
QuickSort(a, low, k-1);
QuickSort(a, k+1, high);
delay(1);
}

void main()
{
int n, a[10000],k;

15 | P a g e Dept. of CSE, Dr. AIT


clock_t st,et;
float ts;
clrscr();
printf("\n Enter How many Numbers:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
QuickSort(a, 1, n);
et=clock();
ts=et-st/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %f",ts);
getch();
}

OUTPUT
1)
Enter Number of elements:
10

The Random Numbers are:


4
-20416
10637
0
2004
512
1098
-20138
10775
10

The Sorted Numbers are:


-20146
-20138
0
4

16 | P a g e Dept. of CSE, Dr. AIT


10
512
1098
2004
10637
10775

The time taken to sort 10 elements is 0.00

2)
Enter the size of array
1000
The time taken to sort 1000 elements is 1.3736

Enter the size of array


2000
The time taken to sort 2000 elements is 2.6923

Enter the size of array


3000
The time taken to sort 3000 elements is 4.0659

Enter the size of array


4000
The time taken to sort 4000 elements is 5.3846

Time Complexity of Quick Sort: O(nlogn)

17 | P a g e Dept. of CSE, Dr. AIT


4. From a given vertex in a weighted connected graph, find shortest
paths to other vertices using Dijkstra's algorithm.

ALGORITHM dijikstra(cost,n,src,dist)
/*This algorithm calculates the shortest path from the given vertex in a weighted
directed graph and gives the path of that vertex to the vertex */

//Input: cost[][] – 2D array gives the weight between each pair ofvertex
// n-The number of vertices in the given weighted directed graph
// src-The vertex from where the path to all other vertex is found
// dist[] -The single dimensional array which gives the minimumdistance from
//the src to all other vertices.
//Output: shortest distance from src to all other vertices

Begin
for i<-0 to n do
dist[i]<-cost[src][i]
visited[i]<-0
end-for
visited[src]<-1
for i<-0 to n do
min<-999
for j<-0 to n do
if(visited[j]=0 and dist[j]<min)
then
min<-dist[j]
u=j
end-if
end-for
for j<-0 to n do
if(visited[j]=0 and (dist[j]+cost[u][j]<dist[j])
then
dist[j]<-dist[u]+cost[u][j]
end-if
end-for
end-for
End

18 | P a g e Dept. of CSE, Dr. AIT


PROGRAM

#include<stdio.h>
#include<conio.h>
void dijkstra(int cost[10][10],int n,int src,int dist[10])
{
int vis[10],u,min,i,j,p[10];
for(i=0;i<n;i++)
{
dist[i]=cost[src][i];
vis[i]=0;
p[i]=src;
}
vis[src]=1;
for(i=0;i<n;i++)
{
min=999;
for(j=0;j<n;j++)
{
if(vis[j]==0 && dist[j]<min)
{
min=dist[j];
u=j;
}
}
vis[u]=1;
for(j=0;j<n;j++)
{
if(vis[j]==0 && (dist[u]+cost[u][j]<dist[j]))
{
dist[j]=dist[u]+cost[u][j];
p[j]=u;
}
}
}
for(i=0;i<n;i++)
{
printf("\n\nShortest path from %d to %d\n",src,i);
j=i;
while(j!=src)
{
printf("%d <- ",j);
j=p[j];
}

19 | P a g e Dept. of CSE, Dr. AIT


printf("%d",j);
printf("::Cost=%d\n",dist[i]);
}
}

void main()
{
int cost[10][10],n,src,dist[10],i,j;
clrscr();
printf("\n\n\n\n\n\n\n Enter the number of vertices:\n");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
}
}
printf("\n Enter the source vertex:");
scanf("%d",&src);
dijkstra(cost,n,src,dist);
getch();
}

OUTPUT
Enter the number of vertices
6
Enter the cost adjacency matrix
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 6 999 4
999 999 6 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999

Enter the source vertex


1
Shortest distance from 1 to 2 is 3
Shortest distance from 1 to 3 is 4
Shortest distance from 1 to 4 is 10
Shortest distance from 1 to 5 is 6
Shortest distance from 1 to 6 is 5

20 | P a g e Dept. of CSE, Dr. AIT


5. Find Minimum Cost Spanning Tree of a given undirected graph
using Kruskal's algorithm
ALGORITHM find(v,parent)
/*This algorithm calculates the parent of v*/
Begin
while(parent[v])
do
v<-parent[v]
endwhile
return v
End

ALGORITHM kruskal(n,cost)
/*This algorithm calculates the minimum cost spanning tree from the given weighted
undirected graph*/
//Input:cost[][]—cost adjacency matrix
// n ----- number of vertices
//Output: minimum spanning tree edges and minimum cost
Begin
for i<-0 to n do
parent[i]<-0
endfor
sum<-0
count=0
while count<n-1
begin
min<-999
for i<-0 to n do
for j<-0 to n
if(i=j) continue
if(cost[i][j]!=0 &&cost[i][j]<min)
then
min=cost[i][j]
u=i
v=j

endif
endfor
endfor
i=find(u,parent)
j=find(v,parent)
if(i!=j)
then
t[k][1]=u
t[k][2]=v
k++
count++
sum+=min

21 | P a g e Dept. of CSE, Dr. AIT


if i<j
then
p[j]=i
else
p[i]=i
end if-else
end if
delete the edge u,v
end while

for i<-1 to n do
write spanning tree
endfor

End

ALGORITHM unions(i,j)
Begin
parent[j]<-i
End

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int find(int v, int p[100])


{
while(p[v]!=v)
v=p[v];
return v;
}

void kruskal( int cost[100][100], int n)


{
int i,j,k,u,v,sum,t[100][2],p[100],mincost,count;
count=0;
k=0;
sum=0;

for(i=0;i<n;i++)
{
p[i]=i;
}

while(count<n-1)
{
mincost=999;

22 | P a g e Dept. of CSE, Dr. AIT


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if((cost[i][j]!=0) && (cost[i][j]<mincost))
{
mincost=cost[i][j];
u=i;
v=j;
}
}
}

if(mincost==999)
break;
i=find(u,p);
j=find(v,p);
if(i!=j)
{
t[k][0]=u;
t[k][1] =v;
k++;
count=count+1;
sum=sum+mincost;
if(i<j)
p[j]=i;
else
p[i]=i;
}
cost[u][v]=cost[v][u]=999;
}
if(count==n-1)
{
printf("\nThe edges of Minimum Cost Spanning Tree are\n\n");
for(i=0;i<n-1;i++)
{
printf("\n%d ->%d ",t[k][0],t[k][1]);
}
printf("\n\tMinimum cost = %d\n",sum);
}
else
printf("\nSpanning tree does not exists");
}

void main()
{
int i,j,cost[100][100],n;
clrscr();

printf("\n\n\tImplementation of Kruskal's algorithm\n\n");


printf("\nEnter the no. of vertices\n");

23 | P a g e Dept. of CSE, Dr. AIT


scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
}
}

Kruskal(cost,n);
getch();
}

OUTPUT

Enter the number of vertices


4
Enter the cost adjacency matrix
0 20 2 999
20 0 15 5
2 15 0 25
999 5 25 0

Cost of the spanning tree is 20


The spanning tree is
13
24
23

24 | P a g e Dept. of CSE, Dr. AIT


6. Find Minimum Cost Spanning Tree of a given undirected graph
using Prim’s algorithm

ALGORITHM : Prim(cost,src,n)
// Prim’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G=(V,E),where src is the source node,
// and cost[][] is the cost adjacency matrix,and n is the number of nodes.
//Output: set of edges composing a minimum spanning tree of G
Begin
sum<-0
min<-999
for i<-0 to n do
for j<-0 to n do
if(cost[i][j]<min)
then
min<-cost[i][j]
src<-i
endif
endfor
endfor
for i<-0 to n do
p[i]<-src
visited[i]<-0
d[i]<-cost[src][i]
endfor
visited[src]<-1
for i<-0 to n do
u=-1
for j<-0 to n do
if(visited[j]=0 and d[j]<min])
then
min<-d[j]
u<-j
endif
endfor
endfor
if u==-1
break;
t[k][0]<-p[u]
t[k][1]<-u
count++
k++
sum+=min

25 | P a g e Dept. of CSE, Dr. AIT


for v<-0 to n do
if(visited[v]=0 and cost[u][v]<d[v])
then
d[v]<-cost[u][v]
p[v]<-u
endif
endfor
End

PROGRAM
#include<stdio.h>
#include<conio.h>

void prim(int cost[100][100],int n,int visited[100],int p[100],int d[100])


{
int mincost,count=0,i,j,v,source,u,t[100][2],k,sum;
k=0;
sum=0;
mincost=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(cost[i][j]<mincost)
{
mincost=cost[i][j];
source=i;
}
}
}
for(i=0;i<n;i++)
{
visited[i]=0;
p[i]=source;
d[i]=cost[source][i];
}
visited[source]=1;
for(i=0;i<n;i++)
{
u=-1;
mincost=999;
for(j=0;j<n;j++)
{
if((visited[j]==0) && (d[j]<mincost))

26 | P a g e Dept. of CSE, Dr. AIT


{
mincost=d[j];
u=j;
}
}
if(u==-1)
break;
visited[u]=1;
t[k][0]=p[u];
t[k][1]=u;
count++;
k++;
sum=sum+mincost;
for(v=0;v<n;v++)
{
if((visited[v]==0) &&(cost[u][v]<d[v]))
{
d[v]=cost[u][v];
p[v]=u;
}
}
}
if(count==n-1)
{

printf("\n Spanning tree exists\nEdges of spanning tree are:\n");


for(i=0;i<n-1;i++)
printf("%d->%d\n",t[i][0],t[i][1]);
printf("Cost of spanning tree: %d",sum);
}
else
printf("Spanning tree doesn't exist\n");
}

void main()
{
int n,j,i,cost[100][100],visited[100],p[100],d[100];
clrscr();
printf("Enter the no. of vertices: ");
scanf("%d",&n);
printf("Enter the cost adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&cost[i][j]);

27 | P a g e Dept. of CSE, Dr. AIT


prim(cost,n,visited,p,d);
getch();
}

OUTPUT

Enter the number of nodes


4
Enter the cost matrix
0 10 20 999
10 0 5 20
20 5 0 50
999 20 50 0

Enter the source node


1
12 is 10
23 i 5
24 is 20
The cost of the spanning tree is 35

28 | P a g e Dept. of CSE, Dr. AIT


7. Obtain the Topological ordering of vertices in a given digraph

ALGORITHM toposort(a,n)
/*algorithm for obtaining the topological ordering of the vertices*/
// Input: a->is the adjacency matrix which is the input to the algorithm
n->number of vertices in the input graph
//Output: Topological ordering of vertices
Begin
for i<- 0 to n-1
do
sum <- 0
for j<-0 to n-1
do
sum <- sum + a[j][i]
end-for
indegree[i] <- sum
end-for

top = -1
k=0
for i <- 0 to n-1
do
if (indegree[i]==0)
then
top <- top+1
s[top] <- i
end-if
end-for
while (top != -1)
do
u < -s[top]
top < -top+1
add u to solution vector t
for each vertex v adjacent to u
decrement indegree[v] by 1
if (indegree[v]==0)
then
top <- top+1
s[top] <- v
end-if
end-for
end-while
write t

29 | P a g e Dept. of CSE, Dr. AIT


return
end

PROGRAM
#include<stdio.h>
#include<conio.h>
#define SIZE 30

int a[SIZE][SIZE], indegree[SIZE];


int n;

void find_indegree()
{
int i,j,sum;

for(i = 0 ; i < n ; i++) // Column sum gives the in-degree of vertex


{
sum = 0 ;
for(j = 0 ; j < n ; j++)
{
sum += a[j][i];
}
indegree[i] = sum;
}
}

void topological_sort()
{
int i,j,u,v,t[SIZE],s[SIZE],top,k;

find_indegree();
top = -1;
k = 0;

for(i = 0 ; i < n; i++) //push vertex with in-degree zero to stack


{
if(indegree[i] == 0)
{
s[++top] = i;
}
}

while(top >= 0) //Repeat until there is an empty in stack


{

30 | P a g e Dept. of CSE, Dr. AIT


u = s[top--];
t[k++] = u; //top of stack element is stored in temporary array

for(v = 0 ; v < n ; v++)


{
if(a[u][v] == 1)
{
indegree[v]--;
if(indegree[v] == 0)
{
s[++top] = v; //push adjacent vertex to stack
}
}
}
}
printf("The topological sequence is \n");
for(i = 0 ; i < n; i++)
{
printf("%d\t", t[i]);
}
}

void main()
{
int i,j;
int u,v;
clrscr();

printf("Enter the number of vertices: \n");


scanf("%d", &n);

printf("Enter the adjacency matrix: \n");


for (i = 0 ; i < n ; i++)
{
for (j = 0;j < n; j++)
{
scanf("%d", &a[i][j]);
}
}

topological_sort();

getch();
}

31 | P a g e Dept. of CSE, Dr. AIT


OUTPUT
Enter the number of vertices:
6
Enter the adjacency matrix:
0 1 0 1 0 0
0 0 1 0 0 0
0 0 0 1 1 0
0 0 0 0 1 0
0 0 0 0 0 0
0 0 0 0 0 0

The Topological Sequence is 5 0 1 2 3 4

32 | P a g e Dept. of CSE, Dr. AIT


8 (a). Implement All-Pairs Shortest Paths Problem using Floyd's
algorithm.

ALGORITHM Floyd(W)
//Implements Floyd’s algorithm for the all-pairs shortest paths problem
//Input: The weight matrix W of a graph
//Output: The distance matrix of shortest paths length
Begin
for i<-0 to n-1
do
for <-0 to n-1
do
D[i,j]<- W[i,j]
end-for
end-for
for k←1 to n do
for i ← 1 to n do
for j ← 1 to n do
D[i,j] ← min (D[i, j], D[i, k]+D[k, j] )
endfor
endfor
endfor
return d
End

PROGRAM
#include<stdio.h>
#include<conio.h>

int min (int a,int b)


{
if(a<b)
return a;
else
return b;
}

void floyd(int a[10][10],int n)


{
int d[10][10],i,j,k;
for(i=1;i<=n;i++)
{

33 | P a g e Dept. of CSE, Dr. AIT


for(j=1;j<=n;j++)
{
d[i][j]=a[i][j];
}
}

for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}

printf("The distance matrix is\n");


for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",d[i][j]);
}
printf("\n");
}
}

void main()
{
int n,a[10][10],i,j;
printf("Enter the number of nodes\n ");
scanf("%d",&n);
printf("Enter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
floyd(a,n);
getch();
}

34 | P a g e Dept. of CSE, Dr. AIT


OUTPUT
Enter the number of nodes
4
Enter the cost adjacency matrix
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0

The distance matrix is


0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0

35 | P a g e Dept. of CSE, Dr. AIT


8 (b). Compute the transitive closure of a given directed graph using
WARSHALL'S algorithm.
ALGORITHM warshall(a,n)
/*This algorithm finds the transitive closure of a given directed graph*/
//Input: a->adjacency matrix of the directed graph
// n->the number of the vertices in the graph
//Output: transitive closure of given graph
Begin
for i<-0 to n-1
do
for <-0 to n-1
do
p[i,j]<-a[i,j]
end-for
end-for
for k<-0 to n-1
do
for i<-0 to n-1
do
for j<-0 to n-1
do
if(p[i,j]=0 and p[i,k]=1 and p[k,j]=1)
then
p[i,j]<-1
end-if
end-for
end-for
end-for
end

PROGRAM
#include<stdio.h>
#include<conio.h>

void warshall(int a[20][20],int n)


{
int i,j,k,p[20][20];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{

36 | P a g e Dept. of CSE, Dr. AIT


p[i][j]=a[i][j];
}
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(p[i][j]==0)
{
if(p[i][k]==1 && p[k][j]==1)
{
p[i][j]=1;
}
}
}
}
}

printf("The transitive closure of the graph is\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",p[i][j]);
}
printf("\n");
}
}

void main()
{
int i,j,n,a[20][20];
clrscr();

printf("Enter the number of vertices\n");


scanf("%d",&n);

printf("Enter the adjacency matrix\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{

37 | P a g e Dept. of CSE, Dr. AIT


scanf("%d",&a[i][j]);
}
}

warshall(a,n);
getch();
}

OUTPUT

Enter the number of vertices


4
Enter the adjacency matrix
0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0

The transitive closure of the graph is


1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1

38 | P a g e Dept. of CSE, Dr. AIT


9. Implement 0/1 Knapsack problem using Dynamic
Programming

ALGORITHM kanpsack(n,w,p,m,v)
/* this algorithm uses dynamic programming technique to solve the knapsack
problem.it accepts the following input*/
//Input: N->number of the jobs.
W[]->wieght of each job.
P[]->profit of each job.
M->capacity of the knapsack.
//Output: the algorithm gives the output 2 dimensional array v[][],
v[N][M] which is the optimal solution.

Begin
for i<-0 to n
do
for j<-0 to n
do
if(i=0 or j=0)
then
v[i,j]=0
else if(w[i]>j)
then
v[i,j]=v[i-1,j]
else
v[i,j]=max(v[i-1,j],v[i-1,j-w[i]]+p[i])
endif
endfor
endfor
End

PROGRAM
#include<stdio.h>
#include<conio.h>

int max(int a, int b)


{
if(a>b)
return a;
else
return b;
}

39 | P a g e Dept. of CSE, Dr. AIT


void knapsack(int n,int m,int w[],int p[])
{
int v[20][20];
int i,j;
for (i=0;i<=n;i++)
{
for (j=0;j<=m;j++)
{
if(i==0 || j==0)
v[i][j]=0;
else if(w[i]>j)
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],(p[i]+v[i-1][j-w[i]]));
}
}

printf("The output is\n");


for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
printf("%d\t",v[i][j]);
}
printf("\n");
}

printf("The optimal solution is %d\n",v[n][m]);

void main()
{
int n,p[10],w[10],m,i,j;
clrscr();

printf("Enter the number of objects\n");


scanf("%d",&n);
printf("Enter the wieghts of each object\n");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("Enter the profit of each object\n");
for(i=1;i<=n;i++)

40 | P a g e Dept. of CSE, Dr. AIT


scanf("%d",&p[i]);
printf("Enter the capacity of the knapsack\n");
scanf("%d",&m);

knapsack(n,m,w,p);

getch();
}

OUTPUT
Enter the number of objects
4
Enter the weights of objects
2
1
3
2
Enter the profit of each object
12
10
20
15
Enter the capacity of knapsack
5
The output is
0 0 0 0 0 0
0 0 12 12 12 12
0 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37

The optimal solution is 37

41 | P a g e Dept. of CSE, Dr. AIT


10. Implement Traveling Salesperson problem using
Dynamic programming.

ALGORITHM TSP(S)
//to find minimum cost trip of salesman
//Input: N- number of vertices, i - starting vertex,
// k - the next vertex to visit, cost adjacency matrix C
// S - set of vertices to be visited
//Output: minimum cost trip
for each of the vertices do
if size of S is ∅
then
g ( i, S ) = Ci1
end if
if size S is greater than or equal to 1
then
g ( i, S ) = min { Cik + g( k, S-{k}) }
end if
endfor

PROGRAM
#include<stdio.h>
#include<conio.h>
int a[10][10],visited[10],n,cost=0;

void tsp(int city)


{
int i,nearcity;
visited[city]=1;
printf("%d -->",city+1);
nearcity=mincost(city);
if(nearcity==999)
{
nearcity=0;
printf("%d",nearcity+1);
cost+=a[city][nearcity];
return;
}
tsp(nearcity);
}

int mincost(int c)

42 | P a g e Dept. of CSE, Dr. AIT


{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i] < min)
{
min=a[i][0]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}

void main()
{
int i,j;
clrscr();
printf("Enter No. of Cities:\n ");
scanf("%d",&n);
printf("Enter Cost adjacency Matrix\n");
for(i=0;i < n;i++)
{
printf("Enter Row %d Elements \n",i+1);
for( j=0;j < n;j++)
scanf("%d",&a[i][j]);
visited[i]=0;
}
printf("The cost matrix:\n");
for( i=0;i < n;i++)
{
for(j=0;j < n;j++)
{
printf("\t%d",a[i][j]);
}
printf("\n");
}
printf("The Path is:\n");
tsp(0);
printf("\nMinimum cost:: %d", cost);

43 | P a g e Dept. of CSE, Dr. AIT


getch();
}

OUTPUT
Enter No. of Cities: 4
Enter Cost adjacency Matrix
Enter Row 1 Elements
0 10 15 20
Enter Row 2 Elements
5 0 9 10
Enter Row 3 Elements
6 13 0 12
Enter Row 4 Elements
8890
The cost matrix:
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
The Path is:
1 --> 2 --> 4 --> 3 --> 1
Minimum cost:: 35

44 | P a g e Dept. of CSE, Dr. AIT


11. Implement Horspool’s algorithm for String Matching using
space & time trade-off concept.
ALGORITHM shift_table(p , s)
//Purpose: To fill the shift table , Based on the pattern string
// Input : P- pattern string to be searched
//Output: t- Shift table is returned through parameter
m= length(p)
for i=0 to 127 do
s [i ]= m
end for
for i=0 to m-2 do
s[p[ i ]]=m-1-i
end for
return

Algorithm Horspool _Pattern_ Matching(p,t)


// Purpose : To check whether the pattern string is present in the text string
//Input : p- Pattern string to be searched
t- Text string where searching takes place
//Output : Position of pattern string p in the text string t,if search is successful,-1
otherwise

Step 1 : [Compute the necessary shifts to be taken]


Shift_table(p,s)
Step 2 : [Align the pattern string with text string]
n <- length(t)
m <- length(p)
Step 3 : [Search or pattern string in text string]
while (i<=n-1) do
k <- 0
while (k<=m-1 and t[i-k]=p[m-1-k]) do
k <- k+1
end while
if (k=m) then
return i-m+1
end if
i <- i + s[t[i]]
end while
return -1

45 | P a g e Dept. of CSE, Dr. AIT


PROGRAM
#include <stdio.h>
#include <string.h>
#define MAX 256

void Shifttable(char p[], int t[])


{
int m, i, j;
m = strlen(p);
for(i=0; i<MAX; i++)
{
t[i]=m;
}
for(j=0; j<m-1; j++)
{
t[p[j]] = m-1-j;
}
}

int Horspool(char s[],char p[],int t[])


{
int i, n, m, k;

n = strlen(s);
m = strlen(p);
i = m-1;
while(i<n)
{
k = 0;
while((k<m)&&(p[m-1-k]==s[i-k]))
k++;
if (k == m)
return i-m+1;
else
i = i+t[s[i]];
}
return -1;
}

void main()
{
char text[MAX];
char pattern[MAX];
int s[MAX];

46 | P a g e Dept. of CSE, Dr. AIT


int pos;
printf("Enter the text string : \n");
gets(text);
printf("Enter the pattern string : \n");
gets(pattern);

Shifttable(pattern,s);
pos = Horspool(text,pattern,s);

if(pos==-1)
printf("\nPattern not found.\n");
else
printf("\nPattern found at position: %d\n",pos+1);

return 0;
}

OUTPUT
1)
Enter the text string
This is the program of horspool string matching
Enter the pattern string
program
Pattern string found at 13 position

2)
Enter the text string
Can you find me
Enter the pattern string
found
Pattern string not found

47 | P a g e Dept. of CSE, Dr. AIT


12. Implement N Queen's problem using Back Tracking
ALGORITHM NQueens (k, n)
//Using backtracking, this procedure prints all possible placements of n queens
//on an n x n chessboard so that they are non-attacking
//x[] is globally declared
Begin
for i ← 1 to n do
if(Place(k,i) )
then
x[k] ← i
if (k=n)
then
write ( x[1...n])
else
Nqueens (k+1, n)
endif
endfor
End

ALGORITHM Place( k, col)


//Returns true if a queen can be placed in kth row and ith column.
// Otherwise it returns false.
// abs(r) returns the absolute value of r.
Begin
for i ← 1 to k do
if ( (x[i]=col or abs(x[i]-col) = abs(i-k) )
then
return false
endif
return true
endfor
End

PROGRAM
#include<stdio.h>
#include<math.h>

int c[20],count=0;
void queen(int k,int n);

48 | P a g e Dept. of CSE, Dr. AIT


int main()
{
int n,i,j;

printf(" - N Queens Problem Using Backtracking -");


printf("\n\nEnter number of Queens:");
scanf("%d",&n);
if(n==2||n==3)
printf("No solution exists");
queen(1,n);
return 0;
}

//function for printing the solution


void print_solution (int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++) //for nxn board
{
if(c[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
printf("\n");
}
}

/*funtion to check conflicts


If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int k,int col)
{
int i;
for(i=1;i<=k-1;i++)
{
//checking column and digonal conflicts
if((c[i]==col) ||(abs(c[i]-col)==abs(i-k)))
return 0;
}
return 1; //no conflict

49 | P a g e Dept. of CSE, Dr. AIT


}

//function to check for proper positioning of queen


void queen(int k,int n)
{
int col;
for(col=1;col<=n;col++)
{
if(place(k,col))
{
c[k]=col; //no conflicts so place queen
if(k==n) //dead end
print_solution(n); //printing the board configuration
else //try queen with next position
queen(k+1,n);
}
}
}

OUTPUT
Enter the number of queens
4
solution 1
x Q x x
x x x Q
Q x x x
x x Q x

solution 2
x x Q x
Q x x x
x x x Q
x Q x x

50 | P a g e Dept. of CSE, Dr. AIT


13. Find a subset of a given set S = {sl,s2,.....,sn} of n positive
integers whose sum is equal to a given positive integer d. For
example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions
{1,2,6}and {1,8}. A suitable message is to be displayed if the given
problem instance doesn't have a solution.
ALGORITHM subset(s,k,total)
/*This algorithm uses backtracking method to find all the solutions of the given
problem. This problem is also called as subset sum problem. */
//Input:s --------> sum of the elements considered for subset
// k --------> kth element of the set
// total ----> total sum of the elements in the set
// a[] -------> elements in the set are stored in array a
//Output:displays subset of elements

Begin
x[k]<-1
if( s+a[k] = m )
then
for i<-1 to k do
if( x[k] = 1)
write a[i]
endfor
endif
else if( s+a[k]+a[k+1] <= m )
then
subset( s+a[k], k+1, total-a[k] )
if ( ( s+total-a[k] >= m ) && ( s+a[k] <=m ) )
then
x[k]<-0
subset( s, k+1, total-a[k] )
endif
return

PROGRAM
#include<stdio.h>
#include<conio.h>

int a[10] , x[10],d ;

void sumofsub ( int , int , int ) ;


void main ()

51 | P a g e Dept. of CSE, Dr. AIT


{
int n , sum = 0;
int i;
clrscr ();
printf ( " \n Enter the size of the set : " ;
scanf ( "%d" , &n );
printf ( " \n Enter the set in increasing order:\n" );
for ( i = 1 ; i <= n ; i++ )
scanf ("%d", &a[i] );
printf ( " \n Enter the value of d : \n " );
scanf ( "%d" , &d );

for ( i = 1 ; i <= n ; i++ )


sum = sum + a[i];

if ( sum < d || a[1] > d )


printf ( " \n No subset possible : " );
else
sumofsub ( 0 , 1 , sum );
getch ();
}

void sumofsub ( int s , int k , int r )


{
int i=1 ; x[k] = 1 ;
if ( ( s + a[k] ) == d )
{
printf("Subset:");
for ( i = 1 ; i <= k ; i++ )
if ( x[i] == 1 )
printf ( "\t%d" , a[i] ) ;
printf ( "\n" ) ;

}
else if ( s + a[k] + a[k+1] <= d )
sumofsub ( s + a[k] , k + 1 , r - a[k] ) ;
if ( ( s + r - a[k] >= d ) && ( s + a[k+1] <=d ) )
{
x[k] = 0;
sumofsub ( s , k + 1 , r - a[k] ) ;
}
}

52 | P a g e Dept. of CSE, Dr. AIT


OUTPUT

Enter the number of elements


5
Enter the elements in the ascending order
1 2 5 6 8
Enter the required sum
9
The solution is
Subset solution=1
1 2 6
Subset solution=2
1 8

53 | P a g e Dept. of CSE, Dr. AIT

You might also like