0% found this document useful (0 votes)
87 views58 pages

CS402 - Lab Manual - ADA

The document provides information about the Analysis and Design of Algorithms course at Gyan Ganga College of Technology, including the course objectives, program objectives and outcomes, list of experiments as per the university, and an enhanced list of experiments by the institute.
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)
87 views58 pages

CS402 - Lab Manual - ADA

The document provides information about the Analysis and Design of Algorithms course at Gyan Ganga College of Technology, including the course objectives, program objectives and outcomes, list of experiments as per the university, and an enhanced list of experiments by the institute.
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/ 58

GYAN GANGA COLLEGE OF TECHNOLOGY, JABALPUR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

Analysis and Design of Algorithm (CS-402)

NAME:

ENROLLMENT NUMBER:

SESSION: 2018-19
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Mission and Vision of the Institution:

Vision of Institute:

Initially to seek autonomy and eventually grow the Institute into a renowned University by:
 Imparting the best technical and professional education to the students of the
Institute.
 Developing all the Departments of the Institute as Centers of Excellence.
 Creating the most congenial and cordial environment of Teaching, Learning
and Research in the Institute.
 Conceiving world - class Education, Ethics and Employability for students in
global perspective.
Mission of Institute
To explore and ensure the best environment to transform students into creative,
knowledgeable, principled engineers and managers compatible with their abilities in ever-
changing socio-economic and competitive scenario by:
 Imparting intensive teaching and training through latest technology
 Motivating the teachers for higher learning and innovative research activities
with social services.
 Generating maximum opportunities for placement of students in National,
Multi-National companies and nurturing entrepreneurship quality.
 Producing highly intellectual citizens through technical education to constitute
an elegant society and meeting social challenges.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Mission and Vision of the Department:

Vision

 To be an innovative and research oriented leading education centre in computer


science and engineering.
 To produce skilful and employable computer science graduates to meet upcoming
social challenges with moral and ethics.
Mission

 To impart intensive, innovative teaching and training through state of art


technology for achieving excellence.
 To associate with industries for identification of social needs and seize
opportunities for software development in live training and sustainable projects of
social challenges.
 Continuous knowledge up-gradation of students, staff, faculty through research,
trainings, seminars, workshops, conferences, webinars and higher studies.
 To impart knowledge of project management, commercial viability and code of
conducts for Engineers
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Program Objectives

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineeringfundamentals, and an engineering specialization to the solution of
complex engineeringproblems.
2. Problem analysis: Identify, formulate, review research literature, and analyze
complexengineering problems reaching substantiated conclusions using first
principles of mathematics,natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering
problems anddesign system components or processes that meet the specified needs
with appropriateconsideration for the public health and safety, and the cultural,
societal, and environmentalconsiderations.
4. Conduct investigations of complex problems: Use research-based knowledge
and researchmethods including design of experiments, analysis and interpretation of
data, and synthesis of theinformation to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modernengineering and IT tools including prediction and modeling to complex
engineering activitieswith an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge
to assesssocietal, health, safety, legal and cultural issues and the consequent
responsibilities relevant tothe professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineeringsolutions in societal and environmental contexts, and demonstrate the
knowledge of, and needfor sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities andnorms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a
member or leaderin diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering
activities with theengineering community and with society at large, such as, being
able to comprehend and writeeffective reports and design documentation, make
effective presentations, and give and receiveclear instructions.
11. Project management and finance: Demonstrate knowledge and understanding
of theengineering and management principles and apply these to one’s own work, as
a member andleader in a team, to manage projects and in multidisciplinary
environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engagein independent and life-long learning in the broadest context of technological
change.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

PSO : Program Specific Outcomes

PSO 1- Able to apply the knowledge gained during the course of the program from
Mathematics, Science & Engineering to solve computation task, and ability to
understand, analyze, design and develop computer programs in the areas related to
algorithms, system software, multi-media, web designing, data analytics and networking.
(PO1, PO2, PO3)

PSO 2- Able to comprehend the technological advancements by lifelong learning and usage
of modern tools for analysis and design of application and system software with varying
complexity. (PO4, PO5, PO12)

PSO 3- Able to communicate effectively in oral and written forms with good leadership
quality, team work, managerial skill to work in multi-disciplinary environment, involve in
development of commercially viable projects, demonstrating the practice of professional
ethics for sustainable development of society. (PO6, PO7, PO8, PO9, PO10, PO11)
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

COURSE OUTCOMES

Once the student has successfully completed this course, he/she will be able to:

CO1: Understand & formulate the time-complexity analysis for an algorithm and analysis
and design of divide & conquer problem solving approach for sorting and searching method.

CO2: understand the greedy strategy & apply it on the problems like optimal merge
patterns, minimum spanning tree & single source shortest path algorithm.

CO3: understand the concept of dynamic programming approach to solve problems &
compare difference between dynamic programming & greedy strategy .

CO4: Understand and design parallel algorithms & understand solutions to problems based
on backtracking approach & also branch & bound approach.

CO5: Understand, Design & implement traversals on trees & searches on graphs and NP
completeness
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

List of Experiments as per the university

1. Write a program for Iterative and Recursive Binary Search.


2. Write a program for Merge Sort.
3. Write a program for Quick Sort.
4. Write a program for Strassen’s Matrix Multiplication.
5. Write a program for optimal merge patterns.
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 Floye-Warshal algorithm.
11. Write a program for traveling salesman problem.
12. Write a program for Hamiltonian cycle problem.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

List of Experiments enhanced by the institute

1. Write a program for Iterative and Recursive Binary Search.


2. Write a program for Merge Sort.
3. Write a program for Quick Sort.
4. Write a program for Strassen’s Matrix Multiplication.
5. Write a program for optimal merge patterns.
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 Floye-Warshal algorithm.
11. Write a program for traveling salesman problem.
12. Write a program for Hamiltonian cycle problem.
13. Write a program for 15 puzzle problem
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Schedule of Practical List Performed (Batch1)

Type of Cov
Sn Name of Experiment Uni Exp. Cat. C PO PS ere Sig
o
t O O d n
Dat
e
1 Write a program for Iterative I Design Core 1 1,2,3,4,5,12 1,2
and Recursive Binary Search.
2 Write a program for Merge I Design Core 1 1,2,3,4,5,12 1,2
Sort.
3 Write a program for Quick I Design Core 1 1,2,3,4,5,12 1,2
Sort.
4 Write a program for I Design Core 1 1,2,3,4,5,12 1,2
Strassen’s Matrix
Multiplication.
5 Write a program for optimal II Design Core 2 1,2,3,4,5,12 1,2
merge patterns.
6 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
Huffman coding.
7 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
minimum spanning trees
using Kruskal’s algorithm.
8 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
minimum spanning trees
using Prim’s algorithm.
9 Write a program for single II Design Core 2 1,2,3,4,5,12 1,2
sources shortest path
algorithm.
10 Write a program for Floye- III Design Core 3 1,2,3,4,5,12 1,2
Warshal algorithm.
11 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2
traveling salesman problem.

12 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2


Hamiltonian cycle problem.
13 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2
Hamiltonian cycle problem.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Schedule of Practical List Performed (Batch2)

Type of Cov
Sn Name of Experiment Uni Exp. Cat. C PO PS ere Sig
o
t O O d n
Dat
e
1 Write a program for Iterative I Design Core 1 1,2,3,4,5,12 1,2
and Recursive Binary Search.
2 Write a program for Merge I Design Core 1 1,2,3,4,5,12 1,2
Sort.
3 Write a program for Quick I Design Core 1 1,2,3,4,5,12 1,2
Sort.
4 Write a program for I Design Core 1 1,2,3,4,5,12 1,2
Strassen’s Matrix
Multiplication.
5 Write a program for optimal II Design Core 2 1,2,3,4,5,12 1,2
merge patterns.
6 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
Huffman coding.
7 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
minimum spanning trees
using Kruskal’s algorithm.
8 Write a program for II Design Core 2 1,2,3,4,5,12 1,2
minimum spanning trees
using Prim’s algorithm.
9 Write a program for single II Design Core 2 1,2,3,4,5,12 1,2
sources shortest path
algorithm.
10 Write a program for Floye- III Design Core 3 1,2,3,4,5,12 1,2
Warshal algorithm.
11 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2
traveling salesman problem.

12 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2


Hamiltonian cycle problem.
13 Write a program for IV Design Core 4 1,2,3,4,5,12 1,2
Hamiltonian cycle problem.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Sr.
No Topics/Sub Topics Date Grade Sign Remark
.
Write a program for Iterative and Recursive
1
Binary Search.
3 Write a program for Merge Sort.

3 Write a program for Quick Sort.


Write a program for Strassen’s Matrix
4
Multiplication.
5 Write a program for optimal merge patterns.
Write a program for Huffman coding.
6
Write a program for minimum spanning
7
trees using Kruskal’s algorithm.
Write a program for minimum spanning
8
trees using Prim’s algorithm.
Write a program for single sources shortest
9
path algorithm.
Write a program for Floye-Warshal
10
algorithm.
Write a program for traveling salesman
11 problem.

Write a program for Hamiltonian cycle


12
problem.
Write a program for Hamiltonian cycle
13
problem.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-01

AIM : Write a program for Iterative and Recursive Binary Search.

ABOUT THE EXPERIMENT: Binary search compares the target value to the middle
element of the array. If they are not equal, the half in which the target cannot lie is
eliminated and the search continues on the remaining half, again taking the middle element
to compare to the target value, and repeating this until the target value is found. If the
search ends with the remaining half being empty, the target is not in the array.

ALGORITHM: Procedure binary_search


A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n

while x not found


if upperBound < lowerBound
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x
set lowerBound = midPoint + 1

if A[midPoint] > x
set upperBound = midPoint - 1

if A[midPoint] = x

EXIT: x found at location midpoint end while end procedure

Software Used: Turbo C / Turbo C++


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

PROGRAM CODE:
#include <stdio.h>
int main()
{ int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break; }
else
last = middle - 1;
middle = (first + last)/2; }
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0; }
OUTPUT:
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-02

AIM : Write a program for Merge Sort.

ABOUT THE EXPERIMENT: Merge Sort is a Divide and Conquer algorithm. It divides
input array in two halves, calls itself for the two halves and then merges the two sorted
halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is
key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two
sorted sub-arrays into one.
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Algorithm: MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)

Program Code:
#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]; }
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

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:
List before sorting
10 14 19 26 27 31 33 35 42 44 0
List after sorting
0 10 14 19 26 27 31 33 35 42 44
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-03

AIM : Write a program for Quick Sort.

ABOUT THE EXPERIMENT: In quick sort ,A large array is partitioned into two arrays
one of which holds values smaller than the specified value, say pivot, based on which the
partition is made and another array holds values greater than the pivot value. quick sort
partitions an array and then calls itself recursively twice to sort the two resulting sub-
arrays.

Algorithm:
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

Program Code:
include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp; } }
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last); } }
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0; }
Output:
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-04

AIM : Write a program for Strassen’s Matrix Multiplication.

ABOUT THE EXPERIMENT: Strassen’s Matrix multiplication can be performed only


on square matriceswhere n is a power of 2. Order of both of the matrices are n × n.

Program Code:

#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++)


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

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++){


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

printf("\n");

for(j = 0;j < 2; j++)

printf("%d\t", c[i][j]); }

return 0; }

Enter the 4 elements of first matrix:

12

34

Enter the 4 elements of second matrix:

56

78

The first matrix is

1 2

3 4

The second matrix is

5 6

7 8

After multiplication using Strassen's algorithm

19 22

43 50
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-05

AIM : Write a program for optimal merge patterns.

ABOUT THE EXPERIMENT: Optimal merge pattern is a pattern that relates to


the merging of two or more sorted files in a single sorted file. This type of merging can be
done by the two-way merging method.

Algorithm:

Algorithm Tree(n)

//list is a global list of n single node

{ For i=1 to i= n-1 do

{ // get a new tree node

Pt: new treenode;

// merge two trees with smallest length

(Pt = lchild) = least(list);

(Pt = rchild) = least(list);

(Pt =weight) = ((Pt = lchild) = weight) = ((Pt = rchild) = weight);

Insert (list , Pt); }

// tree left in list

Return least(list); }

Program Code:

#include<stdio.h>

#include<conio.h>

void main()

{int i,k, a[5],c[5],n,l;

Printf("Enter the no. of elements\t");


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Scanf(“%d”,&n);

Printf("\nEnter the sorted elements for optimal merge pattern");

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

{printf("\t");

Scanf(a[i]);}

i=0;

k=0;

c[k]=a[i]+a[i+1];

i=2;

while(i<n)

{k++;

if((c[k-1]+a[i])<=(a[i]+a[i+1]))

{c[k]=c[k-1]+a[i];}

else{c[k]=a[i]+a[i+1];

i=i+2;

while(i<n)

{ k++;

if((c[k-1]+a[i])<=(c[k-2]+a[i]))

{c[k]=c[k-1]+a[i];}

else{c[k]=c[k-2]+a[i];}

i++;}}

i++;}

k++;

c[k]=c[k-1]+c[k-2];
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

printf(“\n\nThe optimal sum are as follows......\n\n";

for(k=0;k<n-1;k++)

{printf(“%d\t”,c[k]";}

l=0;

for(k=0;k<n-1;k++)

{l=l+c[k];}

Printf("\n\n The external path length is %d."<<l;

getch();}

Output:

Enter the no. of elements 5

Enter the sorted elements for optimal merge pattern 20,30, 10, 5 ,30

The optimal sum are as follows 50,60,65,95,

The external path length is 270


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-06

AIM : Write a program for Huffman coding.

ABOUT THE EXPERIMENT: This algorithm is basically a coding technique for encoding
data such encoded data is used in data compression technique.

Algorithm:

Huffman(c)

{q=c;

For(i=1;i<=n-1;i++)

{temp=getnode();

Left[temp]=getmin(q);

right[temp]=getmin(q);

q=left[temp];

b=roght[temp];

f[temp]=a+b;

insert(a,temp);

} return getmin(q);}

Program Code:

#include<string.h>

#include<stdio.h>

typedef struct node

{ char ch;

int freq;

struct node *left;

struct node *right;


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

}node;

node * heap[100];

int heapSize=0;

void Insert(node * element)

{ heapSize++;

heap[heapSize] = element;

int now = heapSize;

while(heap[now/2] -> freq > element -> freq)

{ heap[now] = heap[now/2];

now /= 2;

} heap[now] = element;

}node * DeleteMin()

{ node * minElement,*lastElement;

int child,now;

minElement = heap[1];

lastElement = heap[heapSize--];

for(now = 1; now*2 <= heapSize ;now = child)

{ child = now*2;

if(child != heapSize && heap[child+1]->freq < heap[child] -> freq )

{ child++;}

if(lastElement -> freq > heap[child] -> freq)

{ heap[now] = heap[child];

} else

{ break; } }
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

heap[now] = lastElement;

return minElement; }

void print(node *temp,char *code)

{ if(temp->left==NULL && temp->right==NULL)

{ printf("char %c code %s\n",temp->ch,code);

return; }

int length = strlen(code);

char leftcode[10],rightcode[10];

strcpy(leftcode,code);

strcpy(rightcode,code);

leftcode[length] = '0';

leftcode[length+1] = '\0';

rightcode[length] = '1';

rightcode[length+1] = '\0';

print(temp->left,leftcode);

print(temp->right,rightcode);

} int main()

{ heap[0] = (node *)malloc(sizeof(node));

heap[0]->freq = 0;

int n ;

printf("Enter the no of characters: ");

scanf("%d",&n);

printf("Enter the characters and their frequencies: ");

char ch;
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

int freq,i;

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

{ scanf(" %c",&ch);

scanf("%d",&freq);

node * temp = (node *) malloc(sizeof(node));

temp -> ch = ch;

temp -> freq = freq;

temp -> left = temp -> right = NULL;

Insert(temp);

} if(n==1)

{ printf("char %c code 0\n",ch);

return 0; }

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

{ node * left = DeleteMin();

node * right = DeleteMin();

node * temp = (node *) malloc(sizeof(node));

temp -> ch = 0;

temp -> left = left;

temp -> right = right;

temp -> freq = left->freq + right -> freq;

Insert(temp);

node *tree = DeleteMin();

char code[10];
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

code[0] = '\0';

print(tree,code);

Output:

f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-07

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

ABOUT THE EXPERIMENT: Kruskal's algorithm is a minimum-spanning-tree


algorithm which finds an edge of the least possible weight that connects any two trees in the
forest. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a
connected weighted graph adding increasing cost arcs at each step.

Algorithm: MST-KRUSKAL(G, w)

A←Ø

for each vertex v V[G]

do MAKE-SET(v)

sort the edges of E into nondecreasing order by weight w

for each edge (u, v) E, taken in nondecreasing order by weight

do if FIND-SET(u) ≠ FIND-SET(v)

then A ← A {(u, v)}

UNION(u, v)

return A

Program Code:

#include<stdio.h>

#include<conio.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);
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

void main()

clrscr();

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

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

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)


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

min=cost[i][j];

a=u=i;

b=v=j;

u=find(u);

v=find(v);

if(uni(u,v))

printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);

mincost +=min;

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

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

getch();

int find(int i)

while(parent[i])

i=parent[i];

return i;
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

int uni(int i,int j)

if(i!=j)

parent[j]=i;

return 1;

return 0;

}
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-08

AIM : Write a program for minimum spanning trees using Prim’s algorithm

ABOUT THE EXPERIMENT: Prim's algorithm is a greedy algorithm that finds a


minimum spanning tree for a connected weighted undirected graph. It finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the edges in
the tree is minimized. This algorithm is directly based on the MST( minimum spanning tree)
property.

Algorithm: MST-PRIM(G, w, r)

for each u V [G]

do key[u] ← ∞

π[u] ← NIL

key[r] ← 0

Q ← V [G]

while Q ≠ Ø

do u ← EXTRACT-MIN(Q)

for each v Adj[u]

do if v Q and w(u, v) < key[v]

then π[v] ← u

key[v] ← w(u, v)

Program Code:

#include<stdio.h>

#include<conio.h>

int a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

void main()

{ clrscr();

printf("\nEnter the number of nodes:");

scanf("%d",&n);

printf("\nEnter the 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; }

visited[1]=1;

printf("\n");

while(ne < n)

{for(i=1,min=999;i<=n;i++)

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

if(cost[i][j]< min)

if(visited[i]!=0)

{min=cost[i][j];

a=u=i;

b=v=j; }

if(visited[u]==0 || visited[v]==0)

{printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);

mincost+=min;

visited[b]=1;}
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

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

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

getch();}

Output:

Experiment-09
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

AIM : Write a program for single sources shortest path algorithm.

ABOUT THE EXPERIMENT: in single source shortest path problem the shortest
distance from a single vertex called source is obtained.

Algorithm:

DIJKSTRA(G,s)

INITIALIZE-SINGLE-SOURCE(G, S)

S←Ø

Q ← V[G]

while Q ≠ Ø

do u ← EXTRACT-MIN(Q)

S ← S U {u}

for each vertex v ∈ Adj[u]

do if dist[v] > dist[u] + w(u,v)

then d[v] ←d[u] + w(u,v)

INITIALIZE-SINGLE-SOURCE( Graph g, Node s )

dist[s] = 0;

for each vertex v in Vertices V[G] - s

dist[v] ← ∞

Program Code:

#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

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

void main(){

int G[MAX][MAX], i, j, n, u;

clrscr();

printf("\nEnter the 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);

dijikstra(G,n,u);

getch(); }

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

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

int visited[MAX], count, mindistance, nextnode, i,j;

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];

for(i=0;i< n;i++)
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

{ 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;

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

if(distance[i] < mindistance&&!visited[i])

{ mindistance=distance[i];

nextnode=i; }

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++; }

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

if(i!=startnode)

{ printf("\nDistance of %d = %d", i, distance[i]);

printf("\nPath = %d", i);

j=i;
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

do

{ j=pred[j];

printf(" <-%d", j);}

while(j!=startnode); } }

Output:
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-10

AIM : Write a program for Floyd-Warshal algorithm.

ABOUT THE EXPERIMENT: The Floyd–Warshall algorithmis an algorithm for finding


shortest paths in a weighted graph with positive or negative edge weights (but with no
negative cycles). A single execution of the algorithm will find the lengths (summed weights)
of shortest paths between all pairs of vertices.

Algorithm:

let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity)

for each edge (u,v)

dist[u][v] ← w(u,v) // the weight of the edge (u,v)

for each vertex v

dist[v][v] ← 0

for k from 1 to |V|

for i from 1 to |V|

for j from 1 to |V|

if dist[i][j] > dist[i][k] + dist[k][j]

dist[i][j] ← dist[i][k] + dist[k][j]

end if

Program Code:
#include<stdio.h>

int i, j, k,n,dist[10][10];

void floydWarshell ()

{ for (k = 0; k < n; k++)


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

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

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

if (dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

} int main()

{ int i,j;

printf("enter no of vertices :");

scanf("%d",&n);

printf("\n");

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

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

{ printf("dist[%d][%d]:",i,j);

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

floydWarshell();

printf (" \n\n shortest distances between every pair of vertices \n");

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

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

printf ("%d\t", dist[i][j]);

printf("\n"); }

return 0; }

Output:-

enter no of vertices :4

dist[0][0]:0

dist[0][1]:8
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

dist[0][2]:999

dist[0][3]:1

dist[1][0]:999

dist[1][1]:0

dist[1][2]:1

dist[1][3]:999

dist[2][0]:4

dist[2][1]:999

dist[2][2]:0

dist[2][3]:999

dist[3][0]:999

dist[3][1]:2

dist[3][2]:9

dist[3][3]:0

shortest distances between every pair of vertices

0 3 4 1

5 0 1 6

4 7 0 5

7 2 3 0

--------------------------------
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-11

AIM : Write a program for traveling salesman problem.

ABOUT THE EXPERIMENT: If there are N cities and cost of travelling from any city to
any other city is given then we have to obtain the cheapest round trip such that each city is
visited exactly once and then returning to the starting city , complete the tour.

Program Code:

#include<stdio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()

{ int i,j;

printf("Enter the number of villages: ");

scanf("%d",&n);

printf("\nEnter the Cost Matrix\n");

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

{ printf("\nEnter Elements of Row: %d\n",i+1);

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

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

completed[i]=0; }

printf("\n\nThe cost list is:");

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

{printf("\n");

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

printf("\t%d",ary[i][j]); } }

void mincost(int city)


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

{int i,ncity;

completed[city]=1;

printf("%d--->",city+1);

ncity=least(city);

if(ncity==999)

{ ncity=0;

printf("%d",ncity+1);

cost+=ary[city][ncity];

return; }

mincost(ncity);}

int least(int c)

{ int i,nc=999;

int min=999,kmin;

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

{ if((ary[c][i]!=0)&&(completed[i]==0))

if(ary[c][i]+ary[i][c] < min)

{ min=ary[i][0]+ary[c][i];

kmin=ary[c][i];

nc=i; } }

if(min!=999)

cost+=kmin;

return nc;}

int main()
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

{ takeInput();

printf("\n\nThe Path is:\n");

mincost(0); //passing 0 because starting vertex

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

return 0; }

Output

Enter the number of villages: 4

Enter the Cost Matrix

Enter Elements of Row: 1


0413

Enter Elements of Row: 2


4021

Enter Elements of Row: 3


1205

Enter Elements of Row: 4


3150
The cost list is:
0413
4021
1205
3150

The Path is:


1—>3—>2—>4—>1

Minimum cost is 7
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-12

AIM : Write a program for Hamiltonian cycle problem.

ABOUT THE EXPERIMENT: given an undirected connected graph and two nodes X and
Y then find a path from X to Y visiting each node in the graph exactly y once.

In the mathematical field of graph theory the Hamiltonian path problem and
the Hamiltonian cycle problem are problems of determining whether a Hamiltonian path (a
path in an undirected or directed graph that visits each vertex exactly once) or
a Hamiltonian cycle exists in a given graph (whether directed or undirected).

Algorithm:

Algo_isValid(v, k)

Input: Vertex v and position k.

Output: Checks whether placing v in the position k is valid or not.

Begin

if there is no edge between node(k-1) to v, then

return false

if v is already taken, then

return false

return true; //otherwise it is valid

End

cycleFound(node k)

Input: node of the graph.

Output: True when there is a Hamiltonian Cycle, otherwise false.

Begin

if all nodes are included, then

if there is an edge between nodes k and 0, then


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

return true

else

return false;

for all vertex v except starting point, do

if isValid(v, k), then //when v is a valid edge

add v into the path

if cycleFound(k+1) is true, then

return true

otherwise remove v from the path

done

return false

End

Program Code:

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},
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

{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;
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

} 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

Cycle: 0 1 2 4 3 0
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

Experiment-13

AIM : Write a program for 15 puzzle problem

ABOUT THE EXPERIMENT: The 15 Puzzle consists of 15 squares numbered from 1 to 15


that are placed in a 4 by 4 box with one empty position. The objective of the puzzle is to
reposition the squares by sliding them one at a time into a configuration with the numbers
in order. The 15 Puzzle is a sliding puzzle that consists of a 4 by 4 frame of numbered square
tiles in an arbitrary ordering with one space. The objective of the puzzle is to place the tiles
in order, as shown in the figure below, by making sliding moves that use the empty space.

Algorithm:

algorithm Iterative Deepening;

begin

bound := h(root); //if initial bound is heuristic estimate g

repeat

bound := DepthFirstSearch (root; bound); // if perform iterative-deepening

DFS g

until solved;

end.

function DepthFirstSearch (n, bound): integer; //if returns next cost bound g

begin

if h(n) = 0 then begin

solved := true; return (0); //f found a

solution: return cost g

end;

new bound := 1;

for each successor ni of n do begin


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

if c(n; ni) + h(ni) _ bound then

b := c(n; ni) + DepthFirstSearch (ni; bound 󲐀c(n; ni)); //f search deeper g

else b := c(n; ni) + h(ni); f cuto_ g

if solved then return (b);

new bound := min (new bound; b); //f compute next iteration's bound g

end;

return (new bound); //f return next

iteration's bound g

end;

Program Code:

#include<stdio.h>

#include<conio.h>

int m=0,n=4;

int cal(int temp[10][10],int t[10][10])

{ int i,j,m=0;

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

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

{ if(temp[i][j]!=t[i][j])

m++; }

return m;}

int check(int a[10][10],int t[10][10])

{ int i,j,f=1;

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

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


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

if(a[i][j]!=t[i][j])

f=0;

return f; }

void main()

{ int p,i,j,n=4,a[10][10],t[10][10],temp[10][10],r[10][10];

int m=0,x=0,y=0,d=1000,dmin=0,l=0;

clrscr();

printf("\nEnter the matrix to be solved,space with zero :\n");

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

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

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

printf("\nEnter the target matrix,space with zero :\n");

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

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

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

printf("\nEntered Matrix is :\n");

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

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

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

printf("\n"); }

printf("\nTarget Matrix is :\n");

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

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

printf("%d\t",t[i][j]);
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

printf("\n"); }

while(!(check(a,t)))

{ l++;

d=1000;

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

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

{if(a[i][j]==0)

{x=i;

y=j; } }

//To move upwards

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

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

temp[i][j]=a[i][j];

if(x!=0)

{ p=temp[x][y];

temp[x][y]=temp[x-1][y];

temp[x-1][y]=p; }

m=cal(temp,t);

dmin=l+m;

if(dmin < d)

{ d=dmin;

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

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

r[i][j]=temp[i][j]; }
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

//To move downwards

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

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

temp[i][j]=a[i][j];

if(x!=n-1)

{ p=temp[x][y];

temp[x][y]=temp[x+1][y];

temp[x+1][y]=p; }

m=cal(temp,t);

dmin=l+m;

if(dmin < d)

{ d=dmin;

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

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

r[i][j]=temp[i][j]; }

//To move right side

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

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

temp[i][j]=a[i][j];

if(y!=n-1)

{ p=temp[x][y];

temp[x][y]=temp[x][y+1];

temp[x][y+1]=p; }

m=cal(temp,t);
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

dmin=l+m;

if(dmin < d)

{ d=dmin;

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

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

r[i][j]=temp[i][j]; }

//To move left

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

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

temp[i][j]=a[i][j];

if(y!=0)

{ p=temp[x][y];

temp[x][y]=temp[x][y-1];

temp[x][y-1]=p;}

m=cal(temp,t);

dmin=l+m;

if(dmin < d)

{ d=dmin;

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

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

r[i][j]=temp[i][j]; }

printf("\nCalculated Intermediate Matrix Value :\n");

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

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


Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

printf("%d\t",r[i][j]);

printf("\n"); }

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

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

{ a[i][j]=r[i][j];

temp[i][j]=0; }

printf("Minimum cost : %d\n",d); }

getch(); }

Enter the matrix to be solved,space with zero:

1 2 3 4 5 6 0 8 9 10 7 11 13 14 15 12

Enter the target matrix,space with zero :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0

Entered Matrix is :

1 2 3 4

5 6 0 8

9 10 7 11

13 14 15 12

Target Matrix is :

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 0

Calculated Intermediate Matrix Value :

1 2 3 4
Gyan Ganga College of Technology, Jabalpur
Computer Science & Engineering

5 6 7 8

9 10 0 11

13 14 15 12

Minimum cost : 4

Calculated Intermediate Matrix Value :

1 2 3 4

5 6 7 8

9 10 11 0

13 14 15 12

Minimum cost : 4

Calculated Intermediate Matrix Value :

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 0

Minimum cost : 3

You might also like