0% found this document useful (0 votes)
27 views

CIL47 CYL47 AlgorithmLab Manual

The document provides instructions for algorithms programs to be developed using C/C++. It lists 12 programs involving searching, sorting and graph algorithms. Program 1 involves computing the greatest common divisor (GCD) of two numbers using different approaches and calculating their time complexities. Program 2 involves implementing linear and binary search algorithms and displaying their time complexities. Program 3 involves sorting a list of binary numbers using bubble and insertion sort and displaying the sorted output.

Uploaded by

rashmimaruthi2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

CIL47 CYL47 AlgorithmLab Manual

The document provides instructions for algorithms programs to be developed using C/C++. It lists 12 programs involving searching, sorting and graph algorithms. Program 1 involves computing the greatest common divisor (GCD) of two numbers using different approaches and calculating their time complexities. Program 2 involves implementing linear and binary search algorithms and displaying their time complexities. Program 3 involves sorting a list of binary numbers using bubble and insertion sort and displaying the sorted output.

Uploaded by

rashmimaruthi2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Department of Computer Science & Engineering

RAMAIAH (Artificial Intelligence and Machine Learning)


Institute of Technology
& CSE (Cyber Security)

Algorithms Laboratory
COUSE CODE:CIL47/ CYL47 COURSE COORDINATOR: Dr. SINI ANNA ALEX
CREDITS : 0:0:1 SEM: 4
I.A. Marks: 50 SEE Exam Hours: 03 SEE Exam Marks: 50
Develop the following program using C/C++ Programming Language
Sl. List of Programs CO PO
No.
1. Design and Implement an algorithm for computing Greatest Common divisor (GCD) of 2 numbers, 1 1,2
say m and n, using the following approaches.
i. Middle school procedure
ii. Euclid’s Algorithm by Division
iii. Euclid’s Algorithm by Subtraction
Compute the Time Complexity for each and Display the GCD (m, n) where m>n.
2. Design and Implement algorithm for searching techniques Linear Search and Binary Search. Com- 1 1,2
pute the Time Complexity and Display.
3. Consider the problem: You have a row of binary digits arranged randomly. Arrange them in such an 1,2 1,2
order that all 0’s precede all 1’s or vice-versa. The only constraint in arranging them is that you are ,3
allowed to interchange the positions of binary digits if they are not similar.
 Implement an algorithm for Bubble sort and Insertion sort for binary value as input like
1 1 0 1 0 1 0 0 0.
 Compute the Time Complexity and Display the output as 0 0 0 0 0 1 1 1 1.
4. Design and Implement a Merge Sort algorithm to sort a given set of elements and determine the 1,2 1,2
time required to sort the elements. Repeat the experiment for different values of n, the number of ,3
elements in the list to be sorted. The elements can be read from the user or can be generated using
the random number generator.
5. Design and Implement Quick sort algorithm to sort a given list of unsorted elements in ascending 1,2 1,2
order and determine the time required to sort the elements. Repeat the experiment for different ,3
values of n, the number of elements in the 1st to be sorted and plot a graph of the time taken versus
n. The elements can be read from the user or can be generated using the random number genera-
tor.
6. Design and Implement an algorithm to Print all the nodes reachable from a given starting node in a 1,2 1,2
graph using Breadth First Search (BFS). Use Queue for constructing BFS spanning tree and Display ,3
the BFS traversal order.
7. Design and Implement an algorithm to check whether a given graph is connected or not using Depth 1,2 1,2
First Search (DFS). Use stack for constructing DFS spanning tree traversal and Display the DFS tra- ,3
versal order.
8. Design and Implement Prim’s algorithm using Greedy Technique to display the minimum cost 1,2 1,2
achieved considering the scenario given. ,3
A car driver is given a set of locations to be covered with their distances by a company. Now the
company gives a privilege for the car driver to start at any arbitrary location. The constraint is entire
driving route chosen by the driver should be minimum.
9. Design and Implement an algorithm to find Minimum Cost Spanning Tree of a given undirected 1,2 1,2
graph using Prim’s algorithm. ,3
10. Design and Implement an algorithm to Find Minimum Cost Spanning Tree of a given undirected 1,2 1,2
graph using Kruskal’s algorithm ,3
11. Design and Implement an algorithm to find the single source shortest path to other vertices using 2,3 1,2
Dijkstra’s algorithm from a given vertex in a weighted connected graph. ,3
12. Design and Implement the Branch and Bound Technique: Find the optimal solution for the Travel- 3 2,3
ling salesman problem.

Department of CSE (AI&ML) and CSE(Cyber Security) Page 1 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

 Note : **Can use CLK_TCK or CLOCKS_PER_SEC

1. Design and Implement an algorithm for computing Greatest Common divisor


(GCD) of 2 numbers, say m and n, using the following approaches.
 Middle school procedure
 Euclid’s Algorithm by Division
 Euclid’s Algorithm by Subtraction
Compute the Time Complexity for each and Display the GCD (m, n) where m>n.

PROGRAM:

#include <iostream>
using namespace std;
#include<time.h>
long int middle_school(long int m,long int n){
long int i,gcd;
clock_t start,end;
start=clock();
for(i=1; i <= m && i <= n; ++i)
{
// Checks if i is factor of both integers
if(m%i==0 && n%i==0)
gcd = i;
}
end=clock();
cout<<endl<<"Time taken:"<<(end-start)/CLOCKS_PER_SEC<<" sec , GCD ";
return gcd;
}

long int euclid(long int m,long int n)


{
clock_t start,end;
start=clock();
long int r;
while(n!=0)
{
r=m%n;
m=n;
n=r;
}
end=clock();
cout<<endl<<"Time taken:"<<(end-start)/CLOCKS_PER_SEC<<" sec , GCD ";
return m;
}

long int sub(long int m,long int n)


{

Department of CSE (AI&ML) and CSE(Cyber Security) Page 2 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
clock_t start,end;
start=clock();
m= (m < 0) ? -m : m;
n = (n < 0) ? -n : n;

while(m != n)
{
if(m > n)
{
m = m - n;
}
else
{
n = n - m;
}
}

end=clock();
cout<<"Time taken :"<<(end-start)/CLOCKS_PER_SEC<<" sec , GCD ";
return m;
} /*End of the function sub*/

main()
{
long int x,y;
cout<<"\t\t ANALYSIS OF THE TWO ALGORITHMS"<<endl<<endl;
cout<<"GCD : "<<endl;
cout<<"enter two numbers:";
cin>>x>>y;
cout<<endl<<endl<<"GCD-Middle School : "<<middle_school(x,y);
cout<<endl<<endl<<"GCD-Euclid : "<<euclid(x,y);
cout<<endl<<endl<<"------------------------------------------------";
cout<<endl<<endl<<"GCD- subtraction : "<<sub(x,y);
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 3 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

2. Design and Implement algorithm for searching techniques Linear Search and Bi-
nary Search. Compute the Time Complexity and Display.

PROGRAM:
#include<iostream>
using namespace std;
#include<time.h>
int Linear_search()
{
int arr[10], n, i, num, index;
clock_t start,end;
cout<<"Linear Search: Enter Number of elements: ";
cin>>n;
cout<<"Enter the Elements";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\n Enter a Number to Search: ";
cin>>num;
start=clock();
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
end=clock();

Department of CSE (AI&ML) and CSE(Cyber Security) Page 4 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

cout<<"Time taken :"<<(end-start)/CLOCKS_PER_SEC<<" sec , Linear Search ";


cout<<endl;
return 0;
}
int Binary_search(){
int i, arr[10], n, num, first, last, middle;
clock_t start,end;
cout<<"Binary Search: Enter number of elements";
cin>>n;
cout<<"Enter Elements (in ascending order): ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nEnter Element to be Search: ";
cin>>num;
start=clock();
first = 0;
last = n-1;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;
break;
}
else

Department of CSE (AI&ML) and CSE(Cyber Security) Page 5 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
end=clock();
cout<<"Time taken :"<<(end-start)/CLOCKS_PER_SEC<<" sec , Binary Search ";
cout<<endl;
return 0;
}

int main()
{
Binary_search();
Linear_search();
}

3. Consider the problem: You have a row of binary digits arranged randomly. Ar-
range them in such an order that all 0’s precede all 1’s or vice-versa. The only
constraint in arranging them is that you are allowed to interchange the positions
of binary digits if they are not similar.
 Implement an algorithm for Bubble sort and Insertion sort for binary value
as input like 1 1 0 1 0 1 0 0 0.
 Compute the Time Complexity and Display the output as 0 0 0 0 0 1 1 1 1.
PROGRAM:
#include<iostream>
using namespace std;
#include<time.h>
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 6 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
void insertionSort(int *array, int size) {
int key, j;
for(int i = 1; i<size; i++) {
key = array[i];//take value
j = i;
while(j > 0 && array[j-1]>key) {
array[j] = array[j-1];
j--;
}
array[j] = key; //insert in right place
}
}
void bubblesort(int *a, int size){
int i, j;
for (i = 0; i < size - 1; i++)

// Last i elements are already


// in place
for (j = 0; j < size - i - 1; j++)
if (a[j] > a[j + 1])
swap(a[j], a[j + 1]);
}
int main() {
int n;
clock_t start,end;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n], a[n]; //create an array with given number of elements

Department of CSE (AI&ML) and CSE(Cyber Security) Page 7 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

cout << "Enter elements: Insertion Sort" << endl;


for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: Insertion Sort ";
display(arr, n);
start=clock();
insertionSort(arr, n);
end=clock();
cout<<"Time taken for Insertion sort:"<<(double)(end-start)/CLOCKS_PER_SEC<<"
sec"<<endl;

cout << "Array after Sorting: Insertion Sort ";


display(arr, n);

cout << "Bubble sort: Enter elements: ";


for(int i = 0; i<n; i++) {
cin >> a[i];
}
display(a, n);
start=clock();
bubblesort(a, n);
end=clock();
cout<<"Time taken for Bubble sort: "<<(double)(end-start)/CLOCKS_PER_SEC<<" sec"<<
endl;
cout << "Array after Sorting: Bubble sort ";
display(a, n);
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 8 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

4. Design and Implement a Merge Sort algorithm to sort a given set of elements and
determine the time required to sort the elements. Repeat the experiment for dif-
ferent values of n, the number of elements in the list to be sorted. The elements
can be read from the user or can be generated using the random number genera-
tor.
/* C++ Program to implement Merge Sorting using Divide and Conquer Algo-
rithm */

PROGRAM:
#include <iostream>
using namespace std;
#include<time.h>

// A function to merge the two half into a sorted data.


void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

// Merge the two parts into temp[].


while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 9 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
else
{
temp[k] = a[j];
k++;
j++;
}
}

// Insert all the remaining values from i to mid into temp[].


while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}

// Insert all the remaining values from j to high into temp[].


while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}

// Assign sorted data stored in temp[] to a[].


for (i = low; i <= high; i++)
{
a[i] = temp[i-low];

Department of CSE (AI&ML) and CSE(Cyber Security) Page 10 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
}

// A function to split array into two parts.


void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);

// Merge them to get sorted output.


Merge(a, low, high, mid);
}
}

int main()
{
int n, i;
clock_t start,end;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{

Department of CSE (AI&ML) and CSE(Cyber Security) Page 11 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

cout<<"Enter element "<<i+1<<": ";


cin>>arr[i];
}

start=clock();

MergeSort(arr, 0, n-1);
end=clock();
cout<<"Time taken for Merge sort: "<<(double)(end-
start)/CLOCKS_PER_SEC<<" sec"<< endl;

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 12 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

5. Design and Implement Quick sort algorithm to sort a given list of unsorted ele-
ments in ascending order and determine the time required to sort the elements.
Repeat the experiment for different values of n, the number of elements in the
1st to be sorted and plot a graph of the time taken versus n. The elements can be
read from the user or can be generated using the random number generator.

/* C++ Program to implement Quick Sorting using Divide and Conquer Algorithm
*/

PROGRAM:
#include<iostream>
using namespace std;
#include<time.h>

void swap(int arr[] , int pos1, int pos2){


int temp;
temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}

int partition(int arr[], int low, int high, int pivot){


int i = low;
int j = low;
while( i <= high){
if(arr[i] > pivot){
i++;
}
else{
swap(arr,i,j);
i++;
j++;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 13 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
}
return j-1;
}

void quicksort(int arr[], int low, int high){


if(low < high){
int pivot = arr[high];
int pos = partition(arr, low, high, pivot);

quicksort(arr, low, pos-1);


quicksort(arr, pos+1, high);
}
}

int main()
{
int n ;
clock_t start,end;

cout << " enter the size of array";


cin>>n;
int arr[n];
cout << " enter the elements";
for( int i = 0 ; i < n; i++){
cin>> arr[i];
}
start=clock();
quicksort(arr, 0 , n-1);

Department of CSE (AI&ML) and CSE(Cyber Security) Page 14 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
end=clock();
cout<<"Time taken for Quick sort: "<<(double)(end-start)/CLOCKS_PER_SEC<<" sec "<<
endl;
cout<<"The sorted array is: ";
for( int i = 0 ; i < n; i++){
cout<< " " <<arr[i];
}
}

6. Design and Implement an algorithm to check whether a given graph is connected


or not using Depth First Search (DFS). Use stack for constructing DFS spanning
tree traversal and Display the DFS traversal order.
PROGRAM:

#include <stdio.h>
#include <stdlib.h>
int a[20][20],vis[20],stack[20], top=-1;
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,j;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);

Department of CSE (AI&ML) and CSE(Cyber Security) Page 15 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

for(i=1;i<=n;i++)
vis[i]=0;
printf("\n D.F.S");
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

dfs(s,n);
}

void dfs(int s,int n)


{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)

Department of CSE (AI&ML) and CSE(Cyber Security) Page 16 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);

Department of CSE (AI&ML) and CSE(Cyber Security) Page 17 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
else
{
k=stack[top--];
return(k);
}
}

7. Design and Implement an algorithm to Print all the nodes reachable from a
given starting node in a graph using Breadth First Search (BFS). Use Queue for
constructing BFS spanning tree and Display the BFS traversal order.

BFS program
#include<stdio.h>
int a[20][20],q[20],visited[20],n,f=-1,r=-1;
void bfs(int v)
{
int i;
for (i=0;i<n;i++) // check all the vertices in the graph
{
if(a[v][i] != 0 && visited[i] == 0) // adjacent to v and not visited
{
r=r+1;
q[r]=i; // insert them into queue
visited[i]=1; // mark the vertex visited
printf("%d ",i);
}
}
f=f+1; // remove the vertex at front of the queue
if(f<=r) // as long as there are elements in the queue
bfs(q[f]); // peform bfs again on the vertex at front of the queue

Department of CSE (AI&ML) and CSE(Cyber Security) Page 18 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
main()
{
int v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=0;i<n;i++) // mark all the vertices as not visited
{
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=0;i<n;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
f=r=0;
q[r]=v;
printf("\n BFS traversal is:\n");
visited[v]=1; // mark the starting vertex as visited
printf("%d ",v);
bfs(v);
if(r != n-1)
printf("\n BFS is not possible");
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 19 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

8. Design and Implement Prim’s algorithm using Greedy technique to display the
minimum cost achieved considering the scenario given.
A car driver is given a set of locations to be covered with their distances by
a company. Now the company gives a privilege for the car driver to start at any
arbitrary location. The constraint is entire driving route chosen by the driver
should be minimum.

9. Design and Implement an algorithm to find Minimum Cost Spanning Tree of a


given undirected graph using Prim’s algorithm.

PROGRAM 8 & 9:

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

#define infinity 9999


#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;

int prims();

int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();

Department of CSE (AI&ML) and CSE(Cyber Security) Page 20 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 21 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];

Department of CSE (AI&ML) and CSE(Cyber Security) Page 22 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

Output:
Enter no. of vertices:5
Enter the adjacency matrix:
01200
10204
22030
00302
04020
spanning tree matrix:

0 1 2 0 0
1 0 0 0 0
2 0 0 3 0
0 0 3 0 2
0 0 0 2 0

Total cost of spanning tree=8

Department of CSE (AI&ML) and CSE(Cyber Security) Page 23 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

10. Design and Implement an algorithm to Find Minimum Cost Spanning Tree of a
given undirected graph using Kruskal’s algorithm

PROGRAM:

KRUSKAL’s using C++

#include<iostream>
#include<string.h>
using namespace std;
class Graph
{
char vertices[10][10];
int cost[10][10],no;
public:
Graph();
void creat_graph();
void display();
int Position(char[]);
void kruskal_algo();
};
/* Initialzing adj matrix with 999 */
/* 999 denotes infinite distance */
Graph::Graph()
{
no=0;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
cost[i][j]=999;
}
}
/* Taking inputs for creating graph */
void Graph::creat_graph()
{
char ans,Start[10],End[10];
int wt,i,j;
cout<<"Enter the number of vertices: ";
cin>>no;
cout<<"\nEnter the vertices: ";
for(i=0;i<no;i++)
cin>>vertices[i];
do
{
cout<<"\nEnter Start and End vertex of the edge: ";
cin>>Start>>End;
cout<<"Enter weight: ";
cin>>wt;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 24 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
i=Position(Start);
j=Position(End);
cost[i][j]=cost[j][i]=wt;
cout<<"\nDo you want to add more edges (Y=YES/N=NO)? : "; /* Type 'Y' or 'y' for
YES and 'N' or 'n' for NO */
cin>>ans;
}while(ans=='y' || ans=='Y');
}
/* Displaying Cost matrix */
void Graph::display()
{
int i,j;
cout<<"\n\nCost matrix: ";
for(i=0;i<no;i++)
{
cout<<"\n";
for(j=0;j<no;j++)
cout<<"\t"<<cost[i][j];
}
}
/* Retrieving position of vertices in 'vertices' array */
int Graph::Position(char key[10])
{
int i;
for(i=0;i<10;i++)
if(strcmp(vertices[i],key)==0)
return i;
return -1;
}
void Graph::kruskal_algo()
{
int i,j,v[10]={0},x,y,Total_cost=0,min,gr=1,flag=0,temp,d;
while(flag==0)
{
min=999;
for(i=0;i<no;i++)
{
for(j=0;j<no;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
x=i;
y=j;
}
}
}
if(v[x]==0 && v[y]==0)
{
v[x]=v[y]=gr;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 25 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
gr++;
}
else if(v[x]!=0 && v[y]==0)
v[y]=v[x];
else if(v[x]==0 && v[y]!=0)
v[x]=v[y];
else
{
if(v[x]!=v[y])
{
d=v[x];
for(i=0;i<no;i++)
{
if(v[i]==d)
v[i]=v[y];
}//end for
}
}
cost[x][y]=cost[y][x]=999;
Total_cost=Total_cost+min; /* calculating cost of minimum spanning tree */
cout<<"\n\t"<<vertices[x]<<"\t\t"<<vertices[y]<<"\t\t"<<min;
temp=v[0]; flag=1;
for(i=0;i<no;i++)
{
if(temp!=v[i])
{
flag=0;
break;
}
}
}
cout<<"\nTotal cost of the tree= "<<Total_cost;
}
int main()
{
Graph g;
g.creat_graph();
g.display();
cout<<"\n\n\nMinimum Spanning tree using kruskal algo=>";
cout<<"\nSource vertex\tDestination vertex\tWeight\n";
g.kruskal_algo();
return 0;
}

Input/Output:
Enter the number of vertices: 5
Enter the vertices: 0 1 2 3 4

Enter Start and End vertex of the edge: 0


1

Department of CSE (AI&ML) and CSE(Cyber Security) Page 26 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
Enter weight: 2

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


2
Enter weight: 3

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


4
Enter weight: 5

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 2


4
Enter weight: 7

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 0


3
Enter weight: 6

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


3
Enter weight: 8

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 3


4
Enter weight: 9
Do you want to add more edges (Y=YES/N=NO)? : n

Cost matrix:
999 2 999 6 999
2 999 3 8 5
999 3 999 999 7
6 8 999 999 9
999 5 7 9 999

Department of CSE (AI&ML) and CSE(Cyber Security) Page 27 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

KRUSKAL’s using C
#include <stdio.h>
#include <stdlib.h>

int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];

int find(int);
int uni(int, int);

void main()
{
printf("Kruskal's algorithm in C\n");
printf("========================\n");

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


scanf("%d", &n);

printf("\nEnter the cost adjacency 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("The edges of Minimum Cost Spanning Tree are\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;
}
}
}

u = find(u);
v = find(v);

if (uni(u, v))

Department of CSE (AI&ML) and CSE(Cyber Security) Page 28 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
{
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
mincost += min;
}

cost[a][b] = cost[b][a] = 999;


}

printf("\nMinimum cost = %d\n", mincost);


}

int find(int i)
{
while (parent[i])
i = parent[i];
return i;
}

int uni(int i, int j)


{
if (i != j)
{
parent[j] = i;
return 1;
}

return 0;
}
Output
Kruskal's algorithm in C
========================
Enter the no. of vertices:
5
Enter the cost adjacency matrix:
01201
10301
23065
00600
11500
The edges of Minimum Cost Spanning Tree are
1 edge (1,2) =1
2 edge (1,5) =1
3 edge (1,3) =2
4 edge (3,4) =6

Minimum cost = 10

Department of CSE (AI&ML) and CSE(Cyber Security) Page 29 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)

11. Design and Implement an algorithm to find the single source shortest path to
other vertices using Dijkstra’s algorithm from a given vertex in a weighted con-
nected graph.
PROGRAM:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];

Department of CSE (AI&ML) and CSE(Cyber Security) Page 30 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;

Department of CSE (AI&ML) and CSE(Cyber Security) Page 31 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 32 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
Output:
Enter no. of vertices:5
Enter the adjacency matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0
Enter the starting node:1
Distance of node0=10
Path=0<-1
Distance of node2=50
Path=2<-1
Distance of node3=40
Path=3<-0<-1
Distance of node4=60
Path=4<-2<-1

12. Design and Implement the Branch and Bound Technique: Find the optimal solu-
tion for the Travelling salesman problem.
PROGRAM:
/*Branch and Bound Algorithm for Travelling Sales Person*/
#include<stdio.h>
#include<conio.h>
int a[10][10],visited[10],n,cost=0;

void get()
{
int i,j;
printf(“Enter No. of Cities: “);

Department of CSE (AI&ML) and CSE(Cyber Security) Page 33 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
scanf(“%d”,&n);
printf(“\nEnter Cost Matrix: \n”);
for( i=0;i<n;i++)
{
printf(“\n Enter Elements of Row # : %d\n”,i+1);
for( j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
visited[i]=0;
}
printf(“\n\nThe cost list is:\n\n”);
for( i=0;i<n;i++)
{
printf(“\n\n”);
for( j=0;j<n;j++)
printf(“\t%d”,a[i][j]);
}
}

void mincost(int city)


{
int i,ncity;
visited[city]=1;
printf(“%d –>”,city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf(“%d”,ncity+1);
cost+=a[city][ncity];

Department of CSE (AI&ML) and CSE(Cyber Security) Page 34 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
return;
}
mincost(ncity);
}

int least(int c)
{
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 put()
{
printf(“\n\nMinimum cost:”);
printf(“%d”,cost);
}

Department of CSE (AI&ML) and CSE(Cyber Security) Page 35 of 36


Department of Computer Science & Engineering
RAMAIAH (Artificial Intelligence and Machine Learning)
Institute of Technology
& CSE (Cyber Security)
void main()
{
clrscr();
get();
printf(“\n\nThe Path is:\n\n”);
mincost(0);
put();
getch();
}
Input Sample:
No. of Nodes : 6

Cost Matrix:
99 10 15 20 99 8
5 99 9 10 8 99
6 13 99 12 99 5
8 8 9 99 6 99
99 10 99 6 99 99
10 99 5 99 99 99

Department of CSE (AI&ML) and CSE(Cyber Security) Page 36 of 36

You might also like