0% found this document useful (0 votes)
38 views61 pages

DAA_LabFile by RaviSir

Uploaded by

Akshat Shishodia
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)
38 views61 pages

DAA_LabFile by RaviSir

Uploaded by

Akshat Shishodia
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/ 61

IMS ENGINEERING COLLEGE

LABORATORY MANUAL
DESIGN & ANALYSIS OF ALGORITHMS
(BCS-553)

B.TECH – III YEAR


(ODD SEM 2024-2025)

Name

Roll No.

Section-Batch

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

IMS ENGINEERING COLLEGE


(Affiliated to Dr A P J Abdul Kalam Technical University, Lucknow )
Approved by AICTE - Accredited by NAAC – ‘A’ Grade
NH#24, Adhyatmik Nagar, Ghaziabad, UP, India
www.imsec.ac.in
Vision and Mission of the Institute
Vision:
To make IMSEC an Institution of Excellence for empowering students through technical
education, incorporating human values, and developing engineering acumen for innovations
and leadership skills to upgrade society.
Mission:
• To promote academic excellence by continuous learning in core and emerging
Engineering domains using innovative teaching and learning methodologies.

• To inculcate values and ethics among the learners.

• To promote industry interactions and cultivate young minds for entrepreneurship.

• To create a conducive learning ecosystem and research environment on a perpetual


basis to develop students as technology leaders and entrepreneurs who can address
tomorrow’s societal needs.
CSE Department Vision and Mission

Vision of the Department

To provide globally competent professionals in the field of Computer Science & Engineering
embedded with sound technical knowledge, aptitude for research and innovation, and nurture
future leaders with ethical values to cater to the industrial & societal needs.
Mission of the Department
Mission 1: To provide quality education in both the theoretical and applied foundations of
Computer Science & Engineering.
Mission 2: Conduct research in Computer Science & Engineering resulting in innovations
thereby nurturing entrepreneurial thinking.
Mission 3: To inculcate team building skills and promote life-long learning with a high
societal and ethical values.

2
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CSE Department Program Educational Objectives (PEOs)

B. Tech Computer Science & Engineering Department has the following Program Educational
Objectives:

PEO1: Possess core theoretical and practical knowledge in Computer Science and Engineering for
successful career development in industry, pursuing higher studies or entrepreneurship.
PEO2: Ability to imbibe life long learning for global challenges to impact society and
environment.
PEO3: To demonstrate work productivity with leadership and managerial skills having ethics and
human value in progressive career path.
PEO4: To exhibit communication skill and collaborative skill plan and participate in
multidisciplinary fields of Computer Science & Engineering.

CSE Department Program Specific Outcomes (PSOs)

B.Tech Computer Science & Engineering Department has the following Program Specific
Outcomes:

PSO1: To analyze and demonstrate, the recent engineering practices, ethical values and strategies
in real time world problems to meet the challenges for the future.
PSO2: To develop adaptive computing system using computational intelligence strategies and
algorithmic design to address diverse challenges in data analysis and machine learning.

3
PROGRAM OUTCOMES
Engineering Graduates will be able to:

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


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering 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 and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader 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 engage
in independent and life-long learning in the broadest context of technological change.

4
GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.

3. Student should enter into the laboratory with:

• Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.

• Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.

• Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.

5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.

6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.

7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.

8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.

9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.

10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat
is kept properly.
DETAILS OF THE EXPERIMENTS CONDUCTED
(TO BE USED BY THE STUDENTS IN THEIR RECORDS)

INDEX

DATE OF FACULTY
S.No TITLE OF THE EXPERIMENT
SUBMISSION SIGNATURE

10
STUDY AND EVALUATION SCHEME

Course Course
Teaching Scheme Credits Assigned
Code Name
Design &
BCS-503(T) Analysis of
Algorthms Theory Practical Tutorial Theory Practical Tutorial Total
BCS-553 (P)

03 02 01 03 01 01 05
(70 (50
Marks) Marks)
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science and Engineering

Course Name: Design & Analysis of Algorithms Lab Course Code: BCS-553
Semester / Year: 5th /3rd NBA Code: C 309

Bloom’s
COURSE OUTCOMES
Level
CO1(C309).1 Implement algorithm to solve problems by iterative approach. K2, K4
CO2(C309).2 Implement algorithm to solve problems by divide and conquer approach K3, K5
CO3(C309).3 Implement algorithm to solve problems by Greedy algorithm approach. K4, K5
Implement algorithm to solve problems by Dynamic programming,
CO4(C309).4 K4, K5
backtracking, branch and bound approach.
CO5(C309).5 Implement algorithm to solve problems by branch and bound approach. K3, K4

CO-PO Matrix

Course PO
PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Outcome 1

C309.1 3 3 3 3 1 1 1 1 2 1 2 2 3 2

C309.2 3 3 3 3 1 1 1 1 2 1 2 2 3 2

C309.3 3 3 2 2 1 2 1 1 2 1 2 2 3 2

C309.4 3 3 3 3 2 2 1 1 2 1 2 2 3 2

C309.5 3 3 2 3 2 2 1 1 2 1 2 2 3 2

C309 3.0 3.0 2.60 2.80 1.40 1.60 1.00 1.00 2.00 1.00 2.00 2.00 3.00 2.00
LIST OF PROGRAMS

Subject: Design & Analysis of Algorithms Lab Code: BCS-553


S.NO. NAME OF EXPERIMENT MAPPING
WITH CO
1 Write a program in C for Sequential Search & Binary Search. C309.1
2 Write a program in C for Heap Sort. C309.1
3 Write a program in C for Merge Sort. C309.1
4 Write a program in C for Selection Sort. C309.1
5 Write a program in C for Insertion Sort. C309.1
6 Write a program in C for Quick Sort. C309.2
7 Knapsack problem using Greedy Solution. C309.2
8 Perform Travelling Salesman Problem. C309.2
9 Write a program in C to find Minimum Spanning Tree using Kruskal’s
Algorithm C309.2

10 Write a program in C to implement N Queen Problem using Backtracking C309.2


11 Sort a given set of n integer elements using Quick Sort method and compute
its time complexity. Run the program for varied values of n> 5000 and record
the time taken to sort. Plot a graph of the time taken versus non graph sheet.
The elements can be read from a file or can be generated using the random C309.2
number generator. Demonstrate using Java how the divide and- conquer
method works along with its time complexity analysis: worst case, average
case and best case.
12 Sort a given set of n integer elements using Merge Sort method and compute
its time complexity. Run the program for varied values of n> 5000, and record
the time taken to sort. Plot a graph of the time taken versus non graph sheet.
The elements can be read from a file or can be generated using the random C309.3
number generator. Demonstrate how the divide and- conquer method works
along with its time complexity analysis: worst case, average case and best
case.
13 Implement , the 0/1 Knapsack problem using (a) Dynamic Programming
C309.3
method (b) Greedy method
14 From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra's algorithm. C309.4
15 Find Minimum Cost Spanning Tree of a given connected undirected graph
using Kruskal's algorithm. Use Union-Find algorithms in your program. C309.5
16 Find Minimum Cost Spanning Tree of a given undirected graph using
Prim’s algorithm. C309.4
17 Write programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm. C309.5
(b) Implement Travelling Sales Person problem using Dynamic
18 Design and implement to find a subset of a given set S = {Sl, S2, ..... ,Sn} of
n positive integers whose SUM is equal to a given positive integer d. For
example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and C309.4
{1,8}. Display a suitable message, if the given problem instance doesn't
have a solution.
19 Design and implement to find all Hamiltonian Cycles in a connected
undirected Graph G of n vertices using backtracking principle C309.4
Experiment No. 1

Write a program in c for sequential search.

Theory Concept:
The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired
element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then
all previous items must be read and checked before the item that matches the search criteria is found.

Implementation:
#include <stdio.h>
#include <stdlib.h> // For exit function

void main() {
int i, temp, ser, a[100];

// Clear screen is not a standard function; remove it or replace with system("cls") for Windows
printf("Enter the number of elements to be entered: ");
scanf("%d", &temp);

// Ensure the number of elements does not exceed the array size
if (temp > 100) {
printf("Number of elements cannot exceed 100.\n");
return;
}

for (i = 0; i < temp; i++) {


printf("\nEnter number %d: ", i + 1);
scanf("%d", &a[i]);
}

printf("Enter the number to be searched: ");


scanf("%d", &ser);

for (i = 0; i < temp; i++) {


if (ser == a[i]) {
printf("\nNumber exists at location %d\n", i + 1);
exit(0); // Exit program as the number is found
}
}

printf("The Number doesn't exist\n");


}
Output:

1.2 Write a program in c for binary search

Theory Concept:
This type of searching an element in the given array, the array should have elements in sorted manner. Each
time the given element is compared with the middle element of given sorted array. And then it is decided to
divide the further the given array.

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

void main() {
int i, temp, ser, a[100], beg = 0, mid, end;

// Input the number of elements


printf("Enter the number of elements to be entered: ");
scanf("%d", &temp);

// Ensure the number of elements does not exceed the array size
if (temp > 100) {
printf("Number of elements cannot exceed 100.\n");
return;
}

// Input elements into the array


printf("Enter the elements in sorted order:\n");
for (i = 0; i < temp; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &a[i]);
}

// Input the number to search


printf("Enter the number to be searched: ");
scanf("%d", &ser);

// Initialize binary search variables


end = temp - 1; // Set `end` to the last index

// Binary search loop


while (beg <= end) {
mid = (beg + end) / 2;

if (ser > a[mid]) {


beg = mid + 1; // Search the right half
} else if (ser < a[mid]) {
end = mid - 1; // Search the left half
} else {
// Element found
printf("The number exists at location %d\n", mid + 1);
exit(0); // Exit the program
}
}

// If the loop ends, the element was not found


printf("The number doesn't exist.\n")
}

Output:
Experiment No. 2

Write a program in c for Heap sort

Theory Concept:
Heap is a complete binary tree. When it is represented as an array for parent node located at nth position left child
and right child are located at 2n and 2n+1 th position. For maxheap larger element is found at parent node and largest
node at root node and vice versa for min heap. For the sorting problem first of all we create max heap by heafying the
given array. then interchange the position of root node and leaf node and remove the leaf node and keep it in an array
which is our resultant sorted array.

Implementation:
#include <stdio.h>

int arr[20], n; // Global array and size of the array

void display();
void create_heap();
void insert(int num, int loc);
void heap_sort();
void del_root(int last);

int main() {
int i;
printf("Enter number of elements: ");
scanf("%d", &n);

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


printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
}

printf("Entered list is:\n");


display();

create_heap();

printf("Heap is:\n");
display();

heap_sort();

printf("Sorted list is:\n");


display();

return 0;
}

/* Function to display the array */


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

/* Function to create a max heap */


void create_heap() {
int i;
for (i = 0; i < n; i++) {
insert(arr[i], i);
}
}

/* Function to insert an element into the heap */


void insert(int num, int loc) {
int par;
while (loc > 0) {
par = (loc - 1) / 2; // Parent index
if (num <= arr[par]) {
arr[loc] = num;
return;
}
arr[loc] = arr[par]; // Move parent down
loc = par; // Move to parent
}
arr[0] = num; // Place the number at the root
}

/* Function to perform heap sort */


void heap_sort() {
int last;
for (last = n - 1; last > 0; last--) {
del_root(last);
}
}

/* Function to delete the root and reheapify */


void del_root(int last) {
int left, right, i, temp, largest;

// Swap root with the last element


temp = arr[0];
arr[0] = arr[last];
arr[last] = temp;

i = 0; // Start from the root


left = 2 * i + 1;
right = 2 * i + 2;

while (left < last) {


// Find the largest among root, left child, and right child
largest = i;
if (arr[left] > arr[largest]) {
largest = left;
}
if (right < last && arr[right] > arr[largest]) {
largest = right;
}

// If the root is the largest, stop reheapifying


if (largest == i) {
return;
}

// Swap with the largest child


temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

// Move down the tree


i = largest;
left = 2 * i + 1;
right = 2 * i + 2;
}
}
Output/Conclusion:
Experiment No. 3

Write a program in c for Merge Sort.

Theory Concept:
It is based on divide and conquers method. It includes
1. Divide the main problem into sub problems.
2. Solve the main problem recursively.
3. Merging the solved sub problems into main solved problem.
Suppose we have an array A with n indices ranging from A0 to An − 1. We apply merge sort to A (A0. Ac − 1) and
A (Ac..An − 1) where c is the integer part of n / 2. When the two halves are returned, they will have been sorted. They
can now be merged together to form a sorted array. In most implementations it is stable, meaning that it preserves the
input order of equal elements in the sorted output.

Implementation:
#include <stdio.h>
#include <math.h>

// Function prototypes
void mergesort(int arr[], int p, int r);
void merge(int arr[], int p, int q, int r);

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

// Input array size


printf("Enter the number of array elements: ");
scanf("%d", &n);

// Input array elements


printf("Enter the array elements:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}

// Perform merge sort


mergesort(a, 0, n - 1);

// Print sorted array


printf("Sorted Array is:\n");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}

// Merge Sort function


void mergesort(int arr[], int p, int r) {
if (p < r) {
int q = (p + r) / 2; // Middle point
// Sort the first half
mergesort(arr, p, q);

// Sort the second half


mergesort(arr, q + 1, r);

// Merge the sorted halves


merge(arr, p, q, r);
}
}

// Merge function
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1; // Size of the left subarray
int n2 = r - q; // Size of the right subarray

int L[n1 + 1], R[n2 + 1]; // Temporary arrays to hold the split data
int i, j, k;

// Copy data into the left and right arrays


for (i = 0; i < n1; i++) {
L[i] = arr[p + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[q + 1 + j];
}

// Add sentinels (large numbers to avoid boundary checks)


L[n1] = 10000; // Sentinel value
R[n2] = 10000; // Sentinel value

// Merge the two arrays back into the original array


i = 0;
j = 0;
for (k = p; k <= r; k++) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
}
}
Output/Conclusion:
Experiment No. 4

Write a program in c for Selection sort.

Theory Concept:
In this sorting is we first find the smallest element and then exchanging it with the first element in array. Then finding
the second smallest element and then placing it on second position in the array and so on.

Implementation:
#include <stdio.h>
#define MAX 25

void main() {
int array[MAX], n, i, j, min_index, temp;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Ensure the number of elements is within the array bounds


if (n > MAX || n <= 0) {
printf("Invalid number of elements. Please enter a value between 1 and %d.\n", MAX);
return;
}

// Input array elements


printf("Enter data to be sorted:\n");
for (i = 0; i < n; i++) {
scanf("%d", &array[i]);
}

// Selection sort implementation


for (i = 0; i < n - 1; i++) {
// Assume the first unsorted element is the smallest
min_index = i;
// Find the smallest element in the remaining unsorted array
for (j = i + 1; j < n; j++) {
if (array[j] < array[min_index]) {
min_index = j;
}
} // Swap the smallest element with the first unsorted element
if (min_index != i) {
temp = array[i];
array[i] = array[min_index];
array[min_index] = temp;
}
}
// Output sorted array
printf("Sorted data is:\n");
for (i = 0; i < n; i++) {
printf("%d\n", array[i]);
}
}
Output:
Experiment No. 5

Write a program in c for Insertion Sort.

Theory Concept:
Let a0, ..., an-1 be the sequence to be sorted. At the beginning and after each iteration of the algorithm the sequence
consists of two parts: the first part a0, ..., ai-1 is already sorted, the second part ai, ..., an-1 is still unsorted (i 0, ...,
n).
In order to insert element ai into the sorted part, it is compared with ai-1, ai-2 etc. When an element aj with aj ai
is found, ai is inserted behind it. If no such element is found, then ai is inserted at the beginning of the sequence.
After inserting element ai the length of the sorted part has increased by one. In the next iteration, ai+1 is inserted
into the sorted part etc. While at the beginning the sorted part consists of element a0 only, at the end it consists of all
elements a0, ..., an-1.

Implementation:
#include <stdio.h>
#define MAX 25

void main() {
int array[MAX], n, i, j, key;

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Ensure the number of elements is within the array bounds


if (n > MAX || n <= 0) {
printf("Invalid number of elements. Please enter a value between 1 and %d.\n", MAX);
return;
}

// Input array elements


printf("\nEnter data to be sorted:\n");
for (i = 0; i < n; i++) {
scanf("%d", &array[i]);
}

// Insertion Sort implementation


for (j = 1; j < n; j++) {
key = array[j];
i = j - 1;

// Shift elements that are greater than `key` to the right


while (i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i--;
}

// Place `key` in its correct position


array[i + 1] = key;
}

// Output sorted array


printf("\nSorted data is:\n");
for (i = 0; i < n; i++) {
printf("%d\n", array[i]);
}
}

Output:
Experiment No. 6

Write a program in C for Quick sort.

Theory Concept:
It is based on divide and conquer paradigm for sorting array. It is the best practical choice for sorting because it is
remarkably efficient on average case: its expected running time is of order of nlogn. It works well in virtual memory.

Implementation:
#include <stdio.h>

// Function prototypes
void quicksort(int a[], int p, int r);
int partition(int a[], int p, int r);

void main() {
int a[10], i, m;

// Input the size of the array


printf("\nEnter the size of the array: ");
scanf("%d", &m);

// Validate the size of the array


if (m <= 0 || m > 10) {
printf("\nInvalid size! Please enter a value between 1 and 10.\n");
return;
}

// Input array elements


printf("\nEnter the array elements:\n");
for (i = 0; i < m; i++) {
scanf("%d", &a[i]);
}

// Perform Quick Sort


quicksort(a, 0, m - 1);

// Output the sorted array


printf("\nSorted array is:\n");
for (i = 0; i < m; i++) {
printf("%d ", a[i]);
}
printf("\n");
}

// Function to perform Quick Sort


void quicksort(int a[], int p, int r) {
if (p < r) {
// Partition the array and get the pivot index
int q = partition(a, p, r);

// Recursively sort the two subarrays


quicksort(a, p, q - 1);
quicksort(a, q + 1, r);
}
}

// Function to partition the array


int partition(int a[], int p, int r) {
int x = a[r]; // Choose the last element as pivot
int i = p - 1; // Index of smaller element
int j, t;

for (j = p; j < r; j++) {


if (a[j] <= x) {
i++;
// Swap a[i] and a[j]
t = a[i];
a[i] = a[j];
a[j] = t;
}
}

// Swap a[i+1] and the pivot (a[r])


t = a[i + 1];
a[i + 1] = a[r];
a[r] = t;

return i + 1; // Return the pivot index


}

Output:
Experiment No. 7

Write a program in c to Knapsack Problem using Greedy Solution

Theory Concept:

There are n items in a store. For i =1,2, . . ., n, item i has weight wi > 0 and worth vi > 0. Thief can carry a maximum
weight of W pounds in a knapsack. In this version of a problem the items can be broken into smaller piece, so the
thief may decide to carry only a fraction xi of object i, where 0 = xi = 1. Item i contributes xiwi to the total weight in
the knapsack, and xivi to the value of the load. In Symbol, the fraction knapsack problem can be stated as follows.
maximize nSi=1 xivi subject to constraint nSi=1 xiwi
= W. It is clear that an optimal solution must fill the knapsack exactly, for otherwise we could add a fraction of one
of the remaining objects and increase the value of the load.

Implementation:
#include <stdio.h>

int n = 5; // Number of objects


int c[10] = {12, 1, 2, 1, 4}; // c[i]: Cost/weight of the ith object
int v[10] = {4, 2, 2, 1, 10}; // v[i]: Value of the ith object
int W = 15; // Maximum weight the knapsack can hold

void simple_fill() {
int cur_w = W; // Current available capacity in the knapsack
float tot_v = 0.0; // Total value of items in the knapsack
int used[10] = {0}; // Keeps track of whether an object is used
int i, maxi;

// While there's room in the knapsack


while (cur_w > 0) {
// Find the object with the maximum value-to-weight ratio
maxi = -1;
for (i = 0; i < n; ++i) {
if (!used[i] && (maxi == -1 || ((float)v[i] / c[i] > (float)v[maxi] / c[maxi]))) {
maxi = i;
}
}

if (maxi == -1) { // No more items can be added


break;
}

used[maxi] = 1; // Mark the object as used


if (cur_w >= c[maxi]) { // If the entire object can be added
cur_w -= c[maxi]; // Reduce the weight capacity
tot_v += v[maxi]; // Add the value of the object
printf("Added object %d (%d$, %dKg) completely in the bag. Space left: %d.\n",
maxi + 1, v[maxi], c[maxi], cur_w);
} else { // If only a fraction of the object can be added
printf("Added %.2f%% (%d$, %dKg) of object %d in the bag.\n",
((float)cur_w / c[maxi]) * 100, v[maxi], c[maxi], maxi + 1);
tot_v += ((float)cur_w / c[maxi]) * v[maxi]; // Add the fractional value
cur_w = 0; // Knapsack is full
}
}

printf("Filled the bag with objects worth %.2f$.\n", tot_v);


}

int main() {
simple_fill();
return 0;
}

Output:
Experiment No. 8

Perform Travelling Salesman Problem

Theory Concept:
Given a complete undirected graph G= (V, E) that has nonnegative integer cost c(u, v) associated with each edge (u,
v) in E, the problem is to find a hamiltonian cycle (tour) of G with minimum cost. A salesperson starts from the city
1 and has to visit six cities (1 through 6) and must come back to the starting city i.e., 1. The first route (left side) 1? 4
? 2 ? 5? 6 ? 3 ? 1 with the total length of 62 km, is a relevant selection but is not the best solution. The second route
(right side) 1 ? 2 ? 5? 4 ? 6 ? 3 ? 1 represents the much better solution as the total distance, 48 km, is less than for the
first route.

Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 20 // Number of cities (19 cities + 1 for a 1-indexed array)

// Function Prototypes
void createProfit(int profitMatrix[N][N]);
void createRoute(int currentRoute[N]);
int evaluateRoute(int currentRoute[N], const int profitMatrix[N][N]);
void tryRoute(int currentRoute[N], int bestRoute[N], const int profitMatrix[N][N]);
void swap(int *item1, int *item2);

int main() {
// Declare necessary variables
int profitMatrix[N][N];
int currentRoute[N], bestRoute[N];
int value = 0;
long int start;
int kount = 0;

// Seed the random number generator


srand(time(0));

// Create a random environment


createRoute(currentRoute);
createRoute(bestRoute);
createProfit(profitMatrix);

// Start timing
start = clock();

// Loop for 60 CPU seconds (60000 milliseconds)


while ((clock() - start) < 60000) {
value = evaluateRoute(currentRoute, profitMatrix);
tryRoute(currentRoute, bestRoute, profitMatrix);
// Display every 10000 cycles
kount++;
if (kount > 10000) {
kount = 0;
printf("Current = %d\tBest = %d\tTime = %ld ms\r",
evaluateRoute(currentRoute, profitMatrix),
evaluateRoute(bestRoute, profitMatrix),
(clock() - start) / CLOCKS_PER_SEC * 1000);
}
}

// Output the best route found


printf("\n\nProfit is: %d\n", evaluateRoute(bestRoute, profitMatrix));
for (int i = 1; i <= 19; i++) {
printf("%d\n", bestRoute[i]);
}
printf("\n\n");

// Grade the route


printf("Grade is: %d\n", (int)((evaluateRoute(bestRoute, profitMatrix) - 14000) * 0.025 + 60));

return 0;
}

// Try a new route and update the best route if necessary


void tryRoute(int currentRoute[N], int bestRoute[N], const int profitMatrix[N][N]) {
int planRoute[N];
int first, second;
static long int tries = 0; // Initializes to zero the first time only

tries++;

// Copy the current route


for (int i = 1; i <= 19; i++) {
planRoute[i] = currentRoute[i];
}

// 90% of the time start over, otherwise make small changes


if (rand() < 32767 * 0.90) {
createRoute(planRoute); // Generate a random route
} else {
// Flip two cities
first = rand() % 19 + 1;
second = rand() % 19 + 1;
swap(&planRoute[first], &planRoute[second]);
}

// Update the current route


for (int i = 1; i <= 19; i++) {
currentRoute[i] = planRoute[i];
}

// Save the best route


if (evaluateRoute(currentRoute, profitMatrix) > evaluateRoute(bestRoute, profitMatrix)) {
tries = 0; // Reset tries counter
for (int i = 1; i <= 19; i++) {
bestRoute[i] = currentRoute[i];
}
}
}

// Evaluate the profit of the current route


int evaluateRoute(int route[N], const int profitMatrix[N][N]) {
int total = 0;
for (int i = 1; i <= 18; i++) {
total += profitMatrix[route[i]][route[i + 1]];
}
total += profitMatrix[route[19]][route[1]]; // Closing the route
return total;
}

// Create a random route


void createRoute(int route[N]) {
for (int i = 1; i <= 19; i++) {
route[i] = i;
}
int numb = rand() % 10 + 5;
for (int i = 1; i <= numb; i++) {
int first = rand() % 19 + 1;
int second = rand() % 19 + 1;
swap(&route[first], &route[second]);
}
}

// Create a random profit matrix


void createProfit(int profitMatrix[N][N]) {
for (int i = 1; i <= 19; i++) {
for (int j = 1; j <= 19; j++) {
profitMatrix[i][j] = rand() % 800 + 100;
}
}
}

// Swap two items


void swap(int *item1, int *item2) {
int temp = *item1;
*item1 = *item2;
*item2 = temp;}
Output:
Experiment No. 9

Write a program in c to find minimal spanning tree using Kruskal’s algorithm.

Theory Concept:
Consider a directed graph, G(N,A), where N and A are the set of nodes and arcs, respectively. Associated with each
arc (i,j) in A is a cost c(i,j). Let |N|=n and |A|=m. The problem is to find a rooted directed spanning tree, G(N,S) where
S is a subset of A such that the sum of c(i,j) for all (i,j) in S is minimized. The rooted directed spanning tree is defined
as a graph which connects, without any cycle, all nodes with n-1 arcs, i.e., each node, except the root, has one and
only one incoming arc.

Implementation:
#include<stdio.h>
#include<conio.h>
#define MAX 10
#define TEMP 0
#define PERM 1
#define FALSE 0
#define TRUE 1
#define infinity 9999

struct node
{
int predecessor;
int dist; /*Distance from predecessor */
int status;
};

struct edge
{
int u;
int v;
};

int adj[MAX][MAX];
int n;

main()
{
int i,j;
int path[MAX];
int wt_tree,count;
struct edge tree[MAX];

create_graph();
printf("Adjacency matrix is :\n");
display();

count = maketree(tree,&wt_tree);

printf("Weight of spanning tree is : %d\n", wt_tree);


printf("Edges to be included in spanning tree are : \n");
for(i=1;i<=count;i++)
{
printf("%d->",tree[i].u);
printf("%d\n",tree[i].v);
}
}/*End of main()*/

create_graph()
{
int i,max_edges,origin,destin,wt;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edges=n*(n-1)/2;

for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d(0 0 to quit) : ",i);
scanf("%d %d",&origin,&destin);
if((origin==0) && (destin==0))
break;
printf("Enter weight for this edge : ");
scanf("%d",&wt);
if( origin > n || destin > n || origin<=0 || destin<=0)
{
printf("Invalid edge!\n");
i--;
}
else
{
adj[origin][destin]=wt;
adj[destin][origin]=wt;
}
}/*End of for*/
if(i {
printf("Spanning tree is not possible\n");
exit(1);
}
}/*End of create_graph()*/

display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",adj[i][j]);
printf("\n");
}
}/*End of display()*/
int maketree(struct edge tree[MAX],int *weight)
{
struct node state[MAX];
int i,k,min,count,current,newdist;
int m;
int u1,v1;
*weight=0;
/*Make all nodes temporary*/
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].dist = infinity;
state[i].status = TEMP;
}
/*Make first node permanent*/
state[1].predecessor=0;
state[1].dist = 0;
state[1].status = PERM;

/*Start from first node*/


current=1;
count=0; /*count represents number of nodes in tree */
while( all_perm(state) != TRUE ) /*Loop till all the nodes become
PERM*/
{
for(i=1;i<=n;i++)
{
if ( adj[current][i] > 0 && state[i].status == TEMP )
{
if( adj[current][i] < state[i].dist )
{
state[i].predecessor = current;
state[i].dist = adj[current][i];
}
}
}/*End of for*/

/*Search for temporary node with minimum distance


and make it current node*/
min=infinity;
for(i=1;i<=n;i++)
{
if(state[i].status == TEMP && state[i].dist < min)
{
min = state[i].dist;
current=i;
}
}/*End of for*/

state[current].status=PERM;

/*Insert this edge(u1,v1) into the tree */


u1=state[current].predecessor;
v1=current;
count++;
tree[count].u=u1;
tree[count].v=v1;
/*Add wt on this edge to weight of tree */
*weight=*weight+adj[u1][v1];
}/*End of while*/
return (count);
}/*End of maketree()*/

/*This function returns TRUE if all nodes are permanent*/


int all_perm(struct node state[MAX] )
{
int i;
for(i=1;i<=n;i++)
if( state[i].status == TEMP )
return FALSE;
return TRUE;
}/*End of all_perm()*/

Output:
Experiment No. 10

Write a program in c to solve n-queen problems

Theory Concept:
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally. A chess board has 8 rows and
8 columns. The standard 8 by 8 Queen's problem asks how to place 8 queens on an ordinary chess board so that none
of them can hit any other in one move.

Implementation:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>

typedef int index;

class nQueens {
public:
nQueens(int n) {
this->n = n;
col = new int[n];
}

~nQueens() {
delete[] col;
}

void start();
void finish();
void queens(index i);
bool promising(index i);
void OutputSolution();

private:
int n;
int *col;
int numSolutions, numNonPromising, numPromising;
};

void nQueens::start() {
numSolutions = 0;
numNonPromising = 0;
numPromising = 0;
queens(0);
}

void nQueens::finish() {
std::cout << "# solutions = " << numSolutions;
std::cout << " # promising nodes = " << numPromising;
std::cout << " # non-promising nodes = " << numNonPromising << std::endl;
}
void nQueens::queens(index i) {
if (promising(i)) {
numPromising++;
if (i == n) {
numSolutions++;
OutputSolution();
} else {
for (index j = 0; j < n; j++) {
col[i] = j;
queens(i + 1);
}
}
} else {
numNonPromising++;
}
}

bool nQueens::promising(index i) {
for (index k = 0; k < i; k++) {
if (col[i] == col[k] || abs(col[i] - col[k]) == i - k) {
return false;
}
}
return true;
}

void nQueens::OutputSolution() {
std::cout << "Solution " << numSolutions << ": ";
for (index i = 0; i < n; i++) {
std::cout << "(" << i + 1 << "," << col[i] + 1 << ") ";
}
std::cout << std::endl;
}

int main(int argc, char *argv[]) {


int n;
std::cout << "n-Queens" << std::endl;
do {
std::cout << "Enter n, or 0 to quit: ";
std::cin >> n;
if (n > 0) {
std::cout << "Solutions for " << n << "-Queens problem:" << std::endl;
nQueens *nq = new nQueens(n);
nq->start();
nq->finish();
delete nq;
}
} while (n > 0);

return 0;
}
Output:
Experiment No. 11

Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus non graph sheet. The elements can be read from a file
or can be generated using the random number generator. Demonstrate using Java how the
divide and- conquer method works along with its time complexity analysis: worst case,
average case and best case.

Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int comparisons = 0; // To count the number of comparisons


int *arr;

void quickSort(int low, int high);


int partition(int low, int high);
void interchange(int i, int j);

int main() {
int n;
printf("Enter n value: ");
scanf("%d", &n);

// Dynamically allocate memory for the array


arr = (int *)malloc(n * sizeof(int));

printf("Quick Sort\n");
printf("1. Best/Average Case\n");
printf("2. Worst Case\n");
int choice;
scanf("%d", &choice);

// Generate array based on the selected case


switch (choice) {
case 1: // Best/Average Case (Random array)
srand(time(NULL)); // Seed for random number generation
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000; // Random numbers between 0 and 999
}
break;
case 2: // Worst Case (Sorted array)
for (int i = 0; i < n; i++) {
arr[i] = i + 1; // Sorted array
}
break;
default:
printf("Invalid choice.\n");
free(arr);
return 0;
}

// Record start time


clock_t start = clock();

// Perform QuickSort
quickSort(0, n - 1);

// Record end time


clock_t end = clock();

// Print sorted array


printf("Sorted Array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Calculate and print time taken for sorting


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time taken (in seconds): %lf\n", time_taken);

// Print the number of comparisons


printf("Number of comparisons: %d\n", comparisons);

// Free dynamically allocated memory


free(arr);

return 0;
}

// QuickSort function to recursively sort the array


void quickSort(int low, int high) {
if (low < high) {
comparisons++;
int j = partition(low, high); // Partitioning step
quickSort(low, j - 1); // Sort the left subarray
quickSort(j + 1, high); // Sort the right subarray
}
}

// Partition function that rearranges elements and returns the pivot index
int partition(int low, int high) {
int pivot = arr[low]; // Pivot element
int i = low, j = high;

while (i < j) {
comparisons++;
// Move i to the right while arr[i] is less than or equal to pivot
while (i < high && arr[i] <= pivot) {
comparisons++;
i++;
}
// Move j to the left while arr[j] is greater than or equal to pivot
while (j > low && arr[j] >= pivot) {
comparisons++;
j--;
}
// If i < j, swap arr[i] and arr[j]
if (i < j) {
comparisons++;
interchange(i, j);
}
}
// Swap pivot into its correct position
interchange(low, j);
return j; // Return pivot index
}

// Function to swap elements at indices i and j


void interchange(int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

Output:
Experiment No. 12

Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program forvaried values of n> 5000, and record the time taken to sort.
Plot a graph of the time taken versus non graph sheet. The elements can be read from a file or
can be generated using the random number generator. Demonstrate how the divide and-
conquer method works along with its time complexity analysis: worst case, average case and
best case.

Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void mergeSort(int a[], int low, int high);


void merge(int a[], int low, int mid, int high);

int main() {
int n;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);

int *a = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for the array
if (a == NULL) {
printf("Memory allocation failed!\n");
return -1;
}

// Generate random numbers for the array


srand(time(0));
for (int i = 0; i < n; i++) {
a[i] = rand() % 2000; // Random integers between 0 and 1999
}

printf("Array elements to be sorted are:\n");


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

// Record start time


clock_t start = clock();

// Call mergeSort
mergeSort(a, 0, n - 1);

// Record end time


clock_t end = clock();

// Print sorted array


printf("\nThe sorted elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");

// Print time taken for sorting


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nThe time taken to sort is %f seconds\n", time_taken);

// Free dynamically allocated memory


free(a);

return 0;
}

// MergeSort function to recursively divide and sort the array


void mergeSort(int a[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;

// Recursively sort the left and right halves


mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);

// Merge the two sorted halves


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

// Merge function to combine two sorted subarrays into one sorted array
void merge(int a[], int low, int mid, int high) {
int i = low, j = mid + 1, k = low;
int *b = (int *)malloc((high - low + 1) * sizeof(int)); // Temporary array for merging

if (b == NULL) {
printf("Memory allocation failed!\n");
exit(-1);
}

// Merge the two halves into the temporary array


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

// If there are remaining elements in the left subarray


while (i <= mid) {
b[k] = a[i];
i++;
k++;
}
// If there are remaining elements in the right subarray
while (j <= high) {
b[k] = a[j];
j++;
k++;
}

// Copy the merged array back into the original array


for (i = low; i <= high; i++) {
a[i] = b[i];
}

// Free the temporary array


free(b);
}
Output:
Experiment No. 13

Implement, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy
method.

Theory Concept:

Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in
the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights
associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the
maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot
break an item, either pick the complete item or don’t pick it (0-1 property).
Given the weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum
total value in the knapsack.
In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or don’t take it.

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

// Structure to represent an item


struct ItemValue {
int weight;
int value;
double cost;
};

// Comparison function to sort items by cost (value/weight ratio)


int compare(const void *a, const void *b) {
struct ItemValue *itemA = (struct ItemValue *)a;
struct ItemValue *itemB = (struct ItemValue *)b;
return (itemB->cost > itemA->cost) - (itemA->cost > itemB->cost);
}

// Function to solve the fractional knapsack problem


double getMaxValue(int weight[], int value[], int n, int capacity) {
// Create an array of ItemValue
struct ItemValue *items = (struct ItemValue *)malloc(n * sizeof(struct ItemValue));
for (int i = 0; i < n; i++) {
items[i].weight = weight[i];
items[i].value = value[i];
items[i].cost = (double)value[i] / weight[i]; // Calculate value-to-weight ratio
}

// Sort items by value-to-weight ratio in descending order


qsort(items, n, sizeof(struct ItemValue), compare);
double totalValue = 0.0; // Total value accumulated in knapsack
for (int i = 0; i < n; i++) {
int curWt = items[i].weight;
int curVal = items[i].value;

// If the item can be fully taken


if (capacity - curWt >= 0) {
capacity -= curWt;
totalValue += curVal;
} else {
// Take the fraction of the last item
double fraction = (double)capacity / curWt;
totalValue += curVal * fraction;
break;
}
}

// Free dynamically allocated memory for items


free(items);

return totalValue;
}

int main() {
int weight[] = {10, 40, 20, 30};
int value[] = {60, 40, 100, 120};
int capacity = 50;
int n = sizeof(weight) / sizeof(weight[0]);

double maxValue = getMaxValue(weight, value, n, capacity);

printf("Maximum value we can obtain = %.2f\n", maxValue);


return 0;
}
Output:
Experiment No. 14

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

Thoery Concept:

Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given
graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we
generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices
included in the shortest-path tree, other set includes vertices not yet included in the shortest-path tree. At every step
of the algorithm, we find a vertex that is in the other set (set of not yet included) and has minimum distance from the
source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex
to all other vertices in the given graph.

Implementation:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

#define V 9 // Number of vertices in the graph

// A utility function to find the vertex with minimum distance value


// from the set of vertices not yet included in the shortest path tree
int minDistance(int dist[], bool sptSet[]) {
// Initialize min value
int min = INT_MAX, min_index;

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


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[]) {
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}

// Function that implements Dijkstra's Single Source Shortest Path algorithm


// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src) {
int dist[V]; // The output array. dist[i] will hold the shortest distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest path tree
// Initialize all distances as INFINITE and sptSet[] as false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet processed
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the picked vertex


for (int v = 0; v < V; v++) {
// Update dist[v] only if v is not in sptSet, there is an edge from u to v,
// and total weight of path from src to v through u is smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

// Print the constructed distance array


printSolution(dist);
}

// Driver program to test the above function


int main() {
// Let us create the example graph discussed above
int graph[V][V] = {
{ 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};

// Run Dijkstra's algorithm from vertex 0


dijkstra(graph, 0);

return 0;
}
OUTPUT:
Experiment No. 15

Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.

Theory Concept:

A Spanning tree is a subset to a connected graph G, where all the edges are connected, i.e, we can traverse to any
edge from a particular edge with or without intermediates. Also, a spanning tree must not have any cycle in it.
Thus, we can say that if there are n vertices in a connected graph then the no. of edges that a spanning tree may have
is n-1.

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

struct Edge {
int src, dest, weight;
};

struct Subset {
int parent, rank;
};

struct Graph {
int V, E;
struct Edge* edges;
};

struct Graph* createGraph(int V, int E) {


struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edges = (struct Edge*)malloc(E * sizeof(struct Edge));
return graph;
}

int find(struct Subset subsets[], int i) {


if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

void Union(struct Subset subsets[], int x, int y) {


int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}

int compareEdges(const void* a, const void* b) {


struct Edge* edgeA = (struct Edge*)a;
struct Edge* edgeB = (struct Edge*)b;
return edgeA->weight - edgeB->weight;
}

void KruskalMST(struct Graph* graph) {


int V = graph->V;
struct Edge result[V];
int e = 0;
int i = 0;
for (i = 0; i < V; ++i)
result[i] = (struct Edge){0, 0, 0};
qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compareEdges);
struct Subset* subsets = (struct Subset*)malloc(V * sizeof(struct Subset));
for (i = 0; i < V; ++i) {
subsets[i].parent = i;
subsets[i].rank = 0;
}
i = 0;
while (e < V - 1) {
struct Edge next_edge = graph->edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
printf("Following are the edges in the constructed MST\n");
int minimumCost = 0;
for (i = 0; i < e; ++i) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
minimumCost += result[i].weight;
}
printf("Minimum Cost Spanning Tree = %d\n", minimumCost);
}

int main() {
int V = 4;
int E = 5;
struct Graph* graph = createGraph(V, E);
graph->edges[0].src = 0;
graph->edges[0].dest = 1;
graph->edges[0].weight = 10;
graph->edges[1].src = 0;
graph->edges[1].dest = 2;
graph->edges[1].weight = 6;
graph->edges[2].src = 0;
graph->edges[2].dest = 3;
graph->edges[2].weight = 5;
graph->edges[3].src = 1;
graph->edges[3].dest = 3;
graph->edges[3].weight = 15;
graph->edges[4].src = 2;
graph->edges[4].dest = 3;
graph->edges[4].weight = 4;
KruskalMST(graph);
return 0;
}

OUTPUT:
Experiment No. 16

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

Theory Concept:
We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm, Prim’s algorithm is
also a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first
set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every
step, it considers all the edges that connect the two sets and picks the minimum weight edge from these edges. After
picking the edge, it moves the other endpoint of the edge to the set containing MST.
Implementation:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 5

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


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

void 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], 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. 17

Write programs to:


(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.

Theory Concept:

The all-pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path
problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the
minimum distance from any node to all other nodes in the graph.

Travelling Salesman Problem (TSP): Given a set of cities and distances between every pair of cities, the problem is
to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference
between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every
city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such
tours exist, the problem is to find a minimum weight Hamiltonian Cycle. For example,
consider the graph shown in the figure on the right side. A TSP tour in the graph is 1-2-4-3-1 The cost of the tour is
10+25+30+15 which is 80. The problem is a famous NP-hard problem. There is no polynomial-time known solution
for this problem.

IMPLEMENTATION:
#include<iostream>
#include<iomanip>
#define NODE 7
#define INF 999
using namespace std;

int costMat[NODE][NODE] = {
{0, 3, 6, INF, INF, INF, INF},
{3, 0, 2, 1, INF, INF, INF},
{6, 2, 0, 1, 4, 2, INF},
{INF, 1, 1, 0, 2, INF, 4},
{INF, INF, 4, 2, 0, 2, 1},
{INF, INF, 2, INF, 2, 0, 1},
{INF, INF, INF, 4, 1, 1, 0}
};

void floydWarshal(){
int cost[NODE][NODE];
for(int i = 0; i < NODE; i++)
for(int j = 0; j < NODE; j++)
cost[i][j] = costMat[i][j];

for(int k = 0; k < NODE; k++){


for(int i = 0; i < NODE; i++) {
for(int j = 0; j < NODE; j++) {
if(cost[i][k] + cost[k][j] < cost[i][j])
cost[i][j] = cost[i][k] + cost[k][j];
}
}
}

cout << "The matrix:" << endl;


for(int i = 0; i < NODE; i++) {
for(int j = 0; j < NODE; j++)
cout << setw(3) << cost[i][j];
cout << endl;
}
}

int main(){
floydWarshal();
return 0;
}

OUTPUT:
Experiment No. 18

Design and implement to find a subset of a given set S = {Sl, S2...., Sn} of n positive integers
whose SUM is equal to a given positive integer d. For example, if S = {1, 2, 5, 6, 8} and d= 9,
there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem
instance doesn't have a solution

Theory Concept:

Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal
to given sum.

Implementation:
#include <stdio.h>
#include <stdbool.h>

bool isSubsetSum(int set[], int n, int sum)


{
if (sum == 0)
return true;
if (n == 0)
return false;
if (set[n - 1] > sum)
return isSubsetSum(set, n - 1, sum);
return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);
}

int main()
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with the given sum\n");
else
printf("No subset with the given sum\n");
return 0;
}

OUTPUT:
Experiment No. 19

Design and implement to find all Hamiltonian Cycles in a connected undirected Graph G
of n vertices using backtracking principle

Theory Concept:

Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or
Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first
vertex of the Hamiltonian Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains,
then prints the path. Following are the input and output of the required function.
Implementation:
#include<stdio.h>

#define V 5

void printSolution(int path[]);

bool isSafe(int v, bool graph[V][V], int path[], int pos)


{
if (graph[path[pos-1]][v] == 0) return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}

bool hamCycleUtil(bool graph[V][V], int path[], int pos)


{
if (pos == V)
{
if (graph[path[pos-1]][path[0]] == 1) return true;
else
return false;
}
for (int v = 1; v < V; v++)
{
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil(graph, path, pos+1) == true) return true;
path[pos] = -1;
}
}
return false;
}

bool hamCycle(bool graph[V][V])


{
int path[V];
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
printf("\nSolution does not exist");
return false;
}

printSolution(path);
return true;
}

void printSolution(int path[])


{
printf("Solution Exists: Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf(" %d ", path[i]);
printf(" %d ", path[0]);
printf("\n");
}

int main()
{
bool graph1[V][V] = {{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}};

hamCycle(graph1);

bool graph2[V][V] = {{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}};
hamCycle(graph2);

return 0;
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy