0% found this document useful (0 votes)
34 views50 pages

ADA Manual

The document describes a lab manual for an analysis and design of algorithms course. It includes details about 12 experiments covering algorithms like binary search, merge sort, quick sort, and graph algorithms. It provides the format, objectives, algorithms, sample codes and expected questions for each experiment.

Uploaded by

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

ADA Manual

The document describes a lab manual for an analysis and design of algorithms course. It includes details about 12 experiments covering algorithms like binary search, merge sort, quick sort, and graph algorithms. It provides the format, objectives, algorithms, sample codes and expected questions for each experiment.

Uploaded by

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

MAHAKAL INSTITUTE OF TECHNOLOGY, UJJAIN

Approved By: All India Council of Technical Education (New Delhi)

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

Name of Student: Abhijeet Shastri

Name of Lab : Analysis Design of Algorithm

Subject Code : CS- 402


Computer Science and
Branch : Engineering

Year/Sem : II/IV

Affiliated to Rajiv Gandhi Prodyogiki Vishwavidyalaya, Bhopal (MP)

INDEX
S. No. Name of Experiment Date Sign Remark

1. Write a program for Iterative Binary Search

2. Write a program for Recursive Binary Search

3. Write a program for Merge Sort

4. Write a program for Quick Sort

5 Write a program for Strassen’s Matrix Multiplication

6 Write a program for Huffman coding

7 Write a program for minimum spanning trees using


Kruskal’s algorithm

8 Write a program for minimum spanning trees using


Prim’s algorithm.

9 Write a program for single sources shortest path


algorithm

10 Write a program for Floyd Warshal algorithm

11 Write a program for traveling salesman problem

12 Write a program for Hamiltonian cycle problem

List of Experiments
Analysis Design of Algorithm (CS- 402)
1. Write a program for Iterative Binary Search.
2. Write a program for Recursive Binary Search.

3. Write a program for Merge Sort.

4. Write a program for Quick Sort.

5. Write a program for Strassen’s Matrix Multiplication.

6. Write a program for Huffman coding.

7. Write a program for minimum spanning trees using Kruskal’s algorithm.

8. Write a program for minimum spanning trees using Prim’s algorithm.

9. Write a program for single sources shortest path algorithm.

10. Write a program for Floyd Warshall algorithm.

11. Write a program for traveling salesman problem.

12. Write a program for Hamiltonian cycle problem.

Lab Manual

Analysis Design of Algorithm (CS-402)

Total number of Experiments: 12


Total number of Turns: 15
S. No. Name of Experiment Turns
needed to
complete
1. Write a program for Iterative Binary Search 1

2. Write a program for Recursive Binary Search 1

3. Write a program for Merge Sort 1

4. Write a program for Quick Sort 1

5 Write a program for Strassen’s Matrix Multiplication 1

6 Write a program for Huffman coding 1


7 Write a program for minimum spanning trees using Kruskal’s algorithm 1

8 Write a program for minimum spanning trees using Prim’s algorithm. 1

9 Write a program for single sources shortest path algorithm 2

10 Write a program for Floyd Warshal algorithm 2

11 Write a program for traveling salesman problem 1

12 Write a program for Hamiltonian cycle problem 2

Distribution of Lab Hours: 1 Hour – 40 Minutes Explanation of


Experiment: 20 Min.
Performance of Experiment: 50 Min. File Checking: 10
Min. Attendance: 05 Min. Viva/Quiz: 05 Min.
Solving of Queries: 10 Min.

DEPLOYMENT OF THE EXPERIMENT:

Turn Deployment
1. Introduction of Lab & explanation of Script
2. Experiment No.1
3. Experiment No.2
4. Experiment No.3
5. Experiment No.4
6. Experiment No.5
7. Experiment No.6
8. Experiment No.7
9. Experiment No.8
10. Experiment No.9
11. Experiment No.9
12. Experiment No.10
13. Experiment No.10
14. Experiment No.11
15. Experiment No.12

SOFTWARE REQUIREMENT:

1. Turbo C++ IDE (TurboC3)


2. Borland Turbo C++ (Version 4.5)

BATCH DISTRIBUTION:

Total Dedicated Individual Computer System: 30 Systems


(Per Batch of 30 Students)

REFERENCE BOOKS:

S. No. Title of the Book Authors Publication


1. Introduction to Algorithm Coreman PHI
2. Analysis & Design of Horowitz & Sahani Pearson
Algorithm
3. Algorithm design & Analysis Udit Agarwal Dhanpat Rai

EXPERIMENT NO. 1
Unit/Topic: 1/Divide & Conquer
PROBLEM DEFINITION:
Write a program for Iterative Binary Search

OBJECTIVE:
To understand working of Binary Search.
ALGORITHM:
1- min := 1;
2- max := N; {array size: var A : array [1..N] of integer}
3- Repeat
4- mid: = (min + max) div 2;
5- if x > A[mid] then min: = mid + 1
6- else max := mid - 1;
7- Until (A[mid] = x) or (min > max);

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is divide & Conquer technique?


Q.2 What are the different ways to implement the binary search?
Q.3 What is difference between binary search & linear search?

NAME OF FACULTY:
SIGNATURE:
DATE:

PROGRAM:

#include<stdio.h>
int iterativeBsearch(int A[], int size, int element); int
main() {
int A[] = {0,12,6,12,12,18,34,45,55,99};
int n=55;
printf("%d is found at Index %d \n",n,iterativeBsearch(A,10,n));
return 0; }
int iterativeBsearch(int A[], int size, int element) {
int start = 0; int end = size-1;
while(start<=end) { int mid = (start+end)/2;
if( A[mid] == element) { return mid;
} else if( element < A[mid] ) {
end = mid-1; } else
{ start = mid+1;
} }
return -1;
}

OUTPUT

EXPERIMENT NO. 2
Unit/Topic: 1/Divide & Conquer
PROBLEM DEFINITION:
Write a program for Recursive Binary Search

OBJECTIVE:
To understand working of Binary Search

ALGORITHM:
1- BinarySearch(A[0..N-1], value, low, high){
2- if (high < low) return -1 // not found
3- mid = low + ((high - low) / 2)
4- if (A[mid] > value) Return BinarySearch (A, value, low, mid-1)
5- else if (A[mid] < value)
6- return BinarySearch(A, value, mid+1, high)
7- else return mid // found }

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is time complexity of binary search?


Q.2 When is a binary search best applied?
Q.3Why binary search is not applied on linked list?

NAME OF FACULTY:
SIGNATURE:
DATE:

PROGRAM:

#include<stdio.h>
int RecursiveBsearch(int A[], int start, int end, int element) {
if(start>end) return -1; int mid = (start+end)/2;
if( A[mid] == element ) return mid; else if( element <
A[mid] )
RecursiveBsearch(A, start, mid-1, element);
else
RecursiveBsearch(A, mid+1, end, element);
} int main()
{
int A[] = {0,2,6,11,12,18,34,45,88,99};
int n=88;
printf("%d is found at Index %d \n",n,RecursiveBsearch(A,0,9,n));
return 0;}

OUTPUT

EXPERIMENT NO. 3
Unit/Topic: 1/Divide & Conquer
PROBLEM DEFINITION:
Write a program for Merge Sort.

OBJECTIVE:
To understand working of Merge sort.

ALGORITHM:
1- Merge sort (A, p, r)
2- if p < r
3- then q = floor ( p + r)/2
4- Merge sort (A, p, q)
5- Merge sort (A, q+1, r)
6- Merge (A, p, q, r)
7- n1 = q-p+1
8- n2 = r-q
9- Create array L [1.. n1+1] and R[1…n2+1]
10- for i = 1 to n1
11- do L[i] = A[p+i-1]
12- for j = 1 to n2
13- do R[j] = A[q+j]
14- L[ n1 + 1] = infinity
15- R[ n2 + 1] = infinity
16- i = 1
17- j=1
18- for k = p to r
19- do if L[i] <= R[j]
20- then A[k] = L[i]
21- i = i + 1
22- else A[k] = R[i]
23- j = j + 1

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is the average case complexity for merge sort algorithm?
Q.2 Given two sorted lists of size m,n ,the number of comparisons needed in the worst case
by the merge sort algorithm is ?
Q.3 what is total numbers of passes in merge sort of ‘n’ numbers is requires?
NAME OF FACULTY:
SIGNATURE:
DATE:

PROGRAM:

#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; int
b[10];

void merging(int low, int mid, int high) {


int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2]) b[i] = a[l1++]; else
b[i] = a[l2++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i <= high; i++)


a[i] = b[i];
}

void sort(int low, int high) {


int mid;

if(low < high) { mid =


(low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else
{ return;
}
}

int main() {
int i;

printf("List before sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");


for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}

OUTPUT

EXPERIMENT NO. 4
Unit/Topic: 1/Divide & Conquer
PROBLEM DEFINITION:
Write a program for Quick Sort.

OBJECTIVE:
To understand working of Quick sort.

ALGORITHM:
1- Quick sort (A, p, r)
2- if p < r
3- then q = Partition ( A, p , r)
4- Quick sort (A, p, q-1)
5- Quick sort (A, q+1, r)
6- Partition (A, p, r)
7- x = A[r]
8- i = p-1
9- for j = p to r-1
10- do if A[j] <= x
11- then i=i+1
12- exchange A[i] = A[j]
11- exchange A[i +1] = A[r]
12- return i+1

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is stable sorting technique?


Q.2 What is time complexity of quick sort?
Q.3 What is pivot element?

NAME OF FACULTY:
SIGNATURE:
DATE:

PROGRAM:

#include <stdio.h> void


swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t; }
int partition(int array[], int low, int high)
{ int pivot = array[high];

int i = (low - 1); for (int j =


low; j < high; j++) {
if (array[j] <= pivot) {

i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}

void quickSort(int array[], int low, int high)


{ if (low < high) {
int pi = partition(array, low, high);

quickSort(array, low, pi - 1);

quickSort(array, pi + 1, high);
}
}

void printArray(int array[], int size) {


for (int i = 0; i < size; ++i)
{ printf("%d ", array[i]);
} printf("\
n"); }

int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");
printArray(data, n);

quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}

OUTPUT

EXPERIMENT NO. 5
Unit/Topic: 1/Divide & Conquer
PROBLEM DEFINITION:
Write a program for Stassen’s Matrix Multiplication

OBJECTIVE:
To understand working of Stassen’s Matrix Multiplication

ALGORITHM:
1- Define a matrix A and B of dimension 2*2.
2- Multiply these two matrix with the help of following formula i.e.C=A*B.
3- M1= (A11+A22) (B11+B22)
4- M2= (A21+A22) B11
5- M3= A11 (B12-B22)
6- M4= A11 (B12-B22)
7- M5= (A11+A12) B22
8 -M6= (A21-A11) (B11+B22)
9 -M7= (A12-A22) (B21+B22)
10- C11=M1+M4-M5+M7
11- C12=M3+M5
12 - C21=M2+M4
13 - C22=M1-M2+M3+M6

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is time complexity of Stassen’s Matrix Multiplication?


Q.2 What is total number of addition and multiplication in Stassen’s Matrix Multiplication?
Q.3 How Stassen’s Matrix Multiplication is applies on 3*3 Matrix

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include<stdio.h> int
main(){
int a[2][2], b[2][2], c[2][2], i, j;
int m1, m2, m3, m4 , m5, m6, m7;

printf("Enter the 4 elements of first matrix: ");


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

printf("Enter the 4 elements of second matrix: ");


for(i = 0; i < 2; i++)
for(j = 0;j < 2; j++)
scanf("%d", &b[i][j]);
printf("\nThe first matrix is\n");
for(i = 0; i < 2; i++)
{ printf("\n"); for(j = 0; j
< 2; j++) printf("%d\t",
a[i][j]);
}

printf("\nThe second matrix is\n");


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

m1= (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);


m2= (a[1][0] + a[1][1]) * b[0][0]; m3= a[0]
[0] * (b[0][1] - b[1][1]); m4= a[1][1] * (b[1]
[0] - b[0][0]); m5= (a[0][0] + a[0][1]) * b[1]
[1]; m6= (a[1][0] - a[0][0]) * (b[0][0]+b[0]
[1]); m7= (a[0][1] - a[1][1]) * (b[1][0]+b[1]
[1]);

c[0][0] = m1 + m4- m5 + m7;


c[0][1] = m3 + m5; c[1][0] =
m2 + m4; c[1][1] = m1 - m2 +
m3 + m6; printf("\nAfter
multiplication using Strassen's
algorithm \n"); for(i = 0; i < 2
; i++){ printf("\n");
for(j = 0;j < 2; j++)
printf("%d\t", c[i][j]);
}

return 0;
}
OUTPUT

EXPERIMENT NO. 6
Unit/Topic: 2/Greedy Algorithm
PROBLEM DEFINITION:
Write a program for Huffman coding.

OBJECTIVE:
To understand implementation of Huffman coding.

ALGORITHM:
1- n=|C|
2- Q=C
3- For i=1 to n-1
4- do
5- Z=allocate Node()
6- X=left[z]=Extract_Min(Q)
7- Y=right[z]=Extract_Min(Q)
8- f[Z]=f[X]+f[Y]
9- Insert (Q, Z)
10- return Extract_Min(Q)

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What do you mean by encoding and decoding?


Q.2 What is time complexity of Huffman encoding?
Q.3 What is greedy Strategy?

NAME OF FACULTY:
SIGNATURE:
DATE:

PROGRAM:

#include <iostream>
#include <vector>
#include <queue>
#include <string>

using namespace std;

class Huffman_Codes
{ struct
New_Node
{ char
data;
size_t freq;
New_Node* left;
New_Node* right;
New_Node(char data, size_t freq) : data(data),
freq(freq),
left(NULL), right(NULL)
{}
~New_Node()
{ delete
left; delete
right;
}
};

struct compare
{
bool operator()(New_Node* l, New_Node* r)
{
return (l->freq > r->freq);
}
};

New_Node* top;

void print_Code(New_Node* root, string str)


{ if(root ==
NULL)
return;

if(root->data == '$')
{
print_Code(root->left, str + "0"); print_Code(root-
>right, str + "1");
}

if(root->data != '$')
{
cout << root->data <<" : " << str << "\n";
print_Code(root->left, str + "0"); print_Code(root->right,
str + "1");
}
}

public:
Huffman_Codes() {};
~Huffman_Codes()
{
delete top;
}
void Generate_Huffman_tree(vector<char>& data, vector<size_t>& freq, size_t size)
{
New_Node* left;
New_Node* right;
priority_queue<New_Node*, vector<New_Node*>, compare > minHeap;

for(size_t i = 0; i < size; ++i)


{
minHeap.push(new New_Node(data[i], freq[i]));
}

while(minHeap.size() != 1)
{
left = minHeap.top(); minHeap.pop();

right = minHeap.top(); minHeap.pop();

top = new New_Node('$', left->freq + right->freq);


top->left = left; top->right = right;
minHeap.push(top);
}
print_Code(minHeap.top(), "");
}
};

int main()
{ int n, f;
char ch;
Huffman_Codes set1; vector<char>
data; vector<size_t> freq; cout<<"Enter
the number of elements \n"; cin>>n;
cout<<"Enter the characters \n"; for (int
i=0;i<n;i++)
{ cin>>ch;
data.insert(data.end(), ch);
}
cout<<"Enter the frequencies \n";
for (int i=0;i<n;i++)
{ cin>>f;
freq.insert(freq.end(), f);
}

size_t size = data.size();


set1.Generate_Huffman_tree(data, freq, size);

return 0;
}
OUTPUT
EXPERIMENT NO. 7
Unit/Topic: 2/Greedy Algorithm
PROBLEM DEFINITION:
Write a program for minimum spanning trees using Kruskal’s algorithm

OBJECTIVE:
To understand implementation of minimum spanning trees using kruskal’s algorithm.

ALGORITHM:
1- A = Ø
2- for each vertex v belongs to V[G]
3- do MAKE-SET(v)
4- Sort the edges of E into nondecreasing order by weight w
5- for each edge (u, v) E, taken in nondecreasing order by weight
6- do if FIND-SET(u) ≠ FIND-SET(v)
7- then A ← A {(u, v)}
8- UNION(u, v)
9- return A

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is Spanning Tree?


Q.2 What is the difference between kruskal & prim’s Algorithm?
Q.3 What is the time complexity of kruskal algorithm?

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include <stdio.h>

#define MAX 30

typedef struct edge {


int u, v, w;
} edge;

typedef struct edge_list {


edge data[MAX];
int n;
} edge_list;

edge_list elist;

int Graph[MAX][MAX], n;
edge_list spanlist;

void kruskalAlgo(); int find(int belongs[], int


vertexno); void applyUnion(int belongs[], int
c1, int c2); void sort();
void print();

void kruskalAlgo() { int


belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

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


i; j++) { if (Graph[i][j] != 0) {
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}

sort();
for (i = 0; i < n; i++)
belongs[i] = i; spanlist.n = 0;

for (i = 0; i < elist.n; i++) { cno1 =


find(belongs, elist.data[i].u); cno2 =
find(belongs, elist.data[i].v);

if (cno1 != cno2)
{ spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}

int find(int belongs[], int vertexno)


{ return (belongs[vertexno]);
}

void applyUnion(int belongs[], int c1, int c2) {


int i;

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


if (belongs[i] == c2)
belongs[i] = c1;
}

void sort() {
int i, j;
edge temp;

for (i = 1; i < elist.n; i++) for (j = 0; j <


elist.n - 1; j++) if (elist.data[j].w >
elist.data[j + 1].w) { temp =
elist.data[j]; elist.data[j] = elist.data[j
+ 1];
elist.data[j + 1] = temp;
}
}
void print()
{ int i, cost =
0;

for (i = 0; i < spanlist.n; i++) {


printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}

printf("\nSpanning tree cost: %d", cost);


}

int main() { int i,


j, total_cost;

n = 6;

Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;

Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;

Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;

Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;

Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;

kruskalAlgo();
print();
}
OUTPUT
EXPERIMENT NO. 8
Unit/Topic: 2/Greedy Algorithm
PROBLEM DEFINITION:
Write a program for minimum spanning trees using Prim’s algorithm

OBJECTIVE:
To understand working of minimum spanning trees using Prim’s algorithm.

ALGORITHM:
1- for each u V [G]
2- do key[u] ← ∞
3- π[u] ← NIL & key[r] ← 0
4- Q ← V [G]
5- while Q ≠ Ø
6- do u ← EXTRACT-MIN(Q)
7- for each v Adj[u]
8- do if v Q and w(u, v) < key[v]
9- then π[v] ← u
10- key[v] ← w(u, v)

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is time complexity of Prim’s algorithm?


Q.2 What is difference between graph and tree?
Q.3 How Prim’s algorithm resembles with Dijkstra’s algorithm?

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include <stdbool.h>
#include <stdio.h>
#define V 5

int minKey(int key[], bool mstSet[])


{
// Initialize min value int min =
INT_MAX, min_index;

for (int v = 0; v < V; v++) if


(mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

int printMST(int parent[], int graph[V][V])


{ printf("Edge \tWeight\
n"); for (int i = 1; i < V;
i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}

void primMST(int graph[V][V])


{ int
parent[V]; int
key[V];
bool mstSet[V];

for (int i = 0; i < V; i++)


key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++) {


int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v]; }

printMST(parent, graph);
}

int main()
{

int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

primMST(graph);

return 0;
}
OUTPUT

EXPERIMENT NO. 9
Unit/Topic: 2/Greedy Algorithm
PROBLEM DEFINITION:
Write a program for single sources shortest path algorithm

OBJECTIVE:
To understand the working of single source shortest path algorithm.

ALGORITHM:
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.

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What is the most commonly used data structure for implementing Dijkstra’s Algorithm?
Q.2 What is the time complexity of Dijikstra’s algorithm?
Q.3 Dijkstra’s Algorithm cannot be applied on which graph?

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include<iostream>
#include<iomanip>
#define V 5 #define
INF 999 using
namespace std; int
costMat[V][V] =
{ {0, 6, INF, 7,
INF},
{INF, 0, 5, 8, -4},
{INF, -2, 0, INF, INF},
{INF, INF, -3, 0, 9},
{2, INF, 7, INF, 0}
}; typedef
struct{ int u, v,
cost; }edge; int
isDiagraph(){
int i, j;
for(i = 0; i<V; i++){ for(j = 0;
j<V; j++){ if(costMat[i][j] !=
costMat[j][i]){ return 1;//graph
is directed
}}}
return 0;//graph is undirected
}
int makeEdgeList(edge *eList){
int count = -1; if(isDiagraph()){ for(int i = 0;
i<V; i++){ for(int j = 0; j<V; j++)
{ if(costMat[i][j] != 0 && costMat[i][j] !=
INF){ count++;//edge find when graph is
directed eList[count].u = i; eList[count].v =
j;
eList[count].cost = costMat[i][j];
}
}
} }els
e{
for(int i = 0; i<V; i++){ for(int j = 0; j<i; j++)
{ if(costMat[i][j] != INF){ count+
+;//edge find when graph is undirected
eList[count].u = i; eList[count].v = j;
eList[count].cost = costMat[i][j];
}
}
}
}
return count+1;
} int bellmanFord(int *dist, int *pred,int
src){ int icount = 1, ecount, max = V*(V-
1)/2; edge edgeList[max]; for(int i = 0;
i<V; i++){ dist[i] = INF; pred[i] = -
1;
}
dist[src] = 0;//for starting vertex, distance is 0
ecount = makeEdgeList(edgeList); while(icount
< V)
{
for(int i = 0; i<ecount; i++)
{ if(dist[edgeList[i].v] > dist[edgeList[i].u] +
costMat[edgeList[i].u][edgeList[i].v]){

dist[edgeList[i].v] = dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v];


pred[edgeList[i].v] = edgeList[i].u;
}
}
icount++;
}

for(int i = 0; i<ecount; i++)


{ if(dist[edgeList[i].v] > dist[edgeList[i].u] +
costMat[edgeList[i].u][edgeList[i].v]){
return 1;//indicates the graph has negative cycle
} }
return 0; }
void display(int *dist, int *pred){
cout << "Vert: "; for(int i = 0;
i<V; i++) cout <<setw(3) <<
i << " "; cout << endl; cout
<< "Dist: ";
for(int i = 0; i<V; i++) cout <<
setw(3) << dist[i] << " "; cout <<
endl; cout << "Pred: "; for(int i =
0; i<V; i++)
cout << setw(3) << pred[i] << " ";
cout << endl;
} int
main(){
int dist[V], pred[V], source, report; source
= 2; report = bellmanFord(dist, pred,
source); cout << "Source Vertex: " <<
source<<endl;
display(dist, pred);
if(report)
cout << "The graph has a negative edge cycle" << endl;
else
cout << "The graph has no negative edge cycle" << endl; }

OUTPUT
EXPERIMENT NO. 10
Unit/Topic: 3/Dynamic Programming
PROBLEM DEFINITION:
Write a program for Floyd-Warshal algorithm

OBJECTIVE:
To understand working of Floyd-Warshal algorithm.

ALGORITHM:
1- Assume a function edgeCost(i,j) which returns the cost of the edge from i to j (infinity if
there is none).
2- A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path from i
to j using intermediate vertices (1..k−1). Each path[i][j] is initialized to edgeCost(i,j) or infinity if
there is no edge between i and j 3- procedure FloydWarshall ()
4- for k := 1 to n
5- for i := 1 to n
6- for j := 1 to n
7- path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What approach is being followed in Floyd Warshall Algorithm?


Q.2 What approach is being followed in Floyd Warshall Algorithm?
Q.3 What procedure is being followed in Floyd Warshall Algorithm??

NAME OF FACULTY:
SIGNATURE:
DATE

PROGRAM:

#include <stdio.h> void


printMatrix(int matrix[][nV]);

void floydWarshall(int graph[][nV]) {


int matrix[nV][nV], i, j, k;

for (i = 0; i < nV; i++) for (j = 0; j < nV; j+


+) matrix[i][j] = graph[i][j]; for (k = 0; k <
nV; k++) { for (i = 0; i < nV; i++) { for (j
= 0; j < nV; j++) { if (matrix[i][k] +
matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
printMatrix(matrix);
}
void printMatrix(int matrix[][nV]) {
for (int i = 0; i < nV; i++) { for
(int j = 0; j < nV; j++) { if
(matrix[i][j] == INF)
printf("%4s", "INF");
else
printf("%4d", matrix[i][j]);
} printf("\
n");
}
}

int main() {
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}};
floydWarshall(graph);
}
OUTPUT
EXPERIMENT NO. 11
Unit/Topic: 4/Branch &Bound
PROBLEM DEFINITION:
Write a program for traveling salesman problem.

OBJECTIVE:
To understand implementation of traveling salesman problem

ALGORITHM:
1- Write the initial cost matrix i.e.Cij = the cost of edge if there is a path between vertex i and vertex
j and Cij = infinity if there is no path.
2- Convert the cost matrix in to reduced matrix i.e. every row and column contain at least one zero
entry.
3- Cost of the reduced matrix is the sum of elements that are subtracted from rows and columns of
cost matrix to make it reduced
4- Calculate the reduced cost matrix for every node
5- if (i,j) to be included then change all entries in row i and column j of A to infinity, set
A[j,1]=infinity & reduce all row and column resulting matrix except from rows and columns
contains infinity
6- calculate the cost of matrix cost = L +cost (i.j) +r
7- repeat the above steps for all node and we get a path

INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What are the different techniques by which traveling salesman problem can be solved?
Q.2 What is time complexity of traveling salesman problem?
Q.3 What is the difference between traveling salesman problem & Dijikstra’s algorithm?

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include <stdio.h>
int matrix[25][25], visited_cities[10], limit, cost = 0;

int tsp(int c) { int count, nearest_city


= 999; int minimum = 999, temp;
for(count = 0; count < limit; count++)
{
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if(matrix[c][count] < minimum)
{
minimum = matrix[count][0] + matrix[c][count];
}
temp = matrix[c][count];
nearest_city = count;
}
}
if(minimum != 999)
{
cost = cost + temp;
}
return nearest_city;
}

void minimum_cost(int city)


{ int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if(nearest_city == 999)
{ nearest_city = 0; printf("%d",
nearest_city + 1); cost = cost +
matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}
int main() {
int i, j;
printf("Enter Total Number of Cities:\t");
scanf("%d", &limit); printf("\nEnter
Cost Matrix\n"); for(i = 0; i < limit; i++)
{
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf("\nEntered Cost Matrix\n");
for(i = 0; i < limit; i++)
{ printf("\n"); for(j =
0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
} } printf("\n\nPath:\t");
minimum_cost(0); printf("\n\
nMinimum Cost: \t");
printf("%d\n", cost); return 0;
}
OUTPUT
EXPERIMENT NO. 12
Unit/Topic: 4/Backtracking
PROBLEM DEFINITION:
Write a program for Hamiltonian cycle problem

OBJECTIVE:
To understand working of Hamiltonian cycle problem.

ALGORITHM:
1- Hamiltonian (k)
{
Repeat
{ //generate value for x[k].
NextValue(k); //Assign a legal next value to x[k].
If(x[k] = 0) then return;
If (k=n) then write (x[1: n]);
Else Hamiltonian(k+1);
} until (false);

2- Next Value(k)
{
Repeat
{
X[k]= (x[k] + 1) mod (n+1); // next vertex.
If (x[k]= 0) then return;
If(G[x[k-1], x[k]!=0) then
{ //is there an edge?
For j=1 to k-1 do if (x[j]=x[k]) then break;
//check for distinctness.
If(j=k) then // if true, then the vertex is distinct.
If((k<n) or ((k=n) and G [x[n], x[1]] !=0))
Then return;
}
} until (false);
}
INPUT SET:

OUTPUT SET:

EXPECTED VIVA QUESTIONS:

Q.1 What do you mean by backtracking algorithm?


Q.2 What is difference between Hamiltonian circuit & Hamiltonian path ?
Q.3 What is time complexity of Hamiltonian problem?

NAME OF FACULTY:
SIGNATURE:
DATE:
PROGRAM:

#include<iostream> #define
NODE 5
using namespace std;

int graph[NODE][NODE] = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};

/* int graph[NODE][NODE] = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
}; */

int path[NODE];

void displayCycle() {
cout<<"Cycle: ";

for (int i = 0; i < NODE; i++)


cout << path[i] << " ";
cout << path[0] << endl; //print the first vertex again
}

bool isValid(int v, int k) {


if (graph [path[k-1]][v] == 0) //if there is no edge
return false;

for (int i = 0; i < k; i++) //if vertex is already taken, skip that
if (path[i] == v) return false; return true;
}
bool cycleFound(int k) {
if (k == NODE) { //when all vertices are in the path
if (graph[path[k-1]][ path[0] ] == 1 )
return true;
else
return false;
}

for (int v = 1; v < NODE; v++) { //for all vertices except starting point
if (isValid(v,k)) { //if possible to add v in the path path[k] =
v;
if (cycleFound (k+1) == true)
return true;
path[k] = -1; //when k vertex will not in the solution
} }
return false;
}

bool hamiltonianCycle()
{ for (int i = 0; i < NODE; i+
+) path[i] = -1;
path[0] = 0; //first vertex as 0

if ( cycleFound(1) == false ) { cout <<


"Solution does not exist"<<endl; return
false;
}

displayCycle();
return true;
}

int main()
{ hamiltonianCycle();
}
OUTPUT

You might also like