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

DAALabfile

The document is a lab file for the Design and Analysis of Algorithms course at Pranveer Singh Institute of Technology, detailing the vision, mission, and educational objectives of the Computer Science & Engineering Department. It includes a list of experiments, course outcomes, and specific algorithms to be implemented and analyzed, such as linear search, binary search, and various sorting algorithms. The document serves as a guide for third-year B.Tech students in their practical coursework for the semester.

Uploaded by

tbnigam
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)
34 views38 pages

DAALabfile

The document is a lab file for the Design and Analysis of Algorithms course at Pranveer Singh Institute of Technology, detailing the vision, mission, and educational objectives of the Computer Science & Engineering Department. It includes a list of experiments, course outcomes, and specific algorithms to be implemented and analyzed, such as linear search, binary search, and various sorting algorithms. The document serves as a guide for third-year B.Tech students in their practical coursework for the semester.

Uploaded by

tbnigam
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

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Even Semester 2024-25

B. Tech.- Third Year

Semester- V

Lab File
Design and Analysis of Algorithm
(BCS 553)

Submitted To : Submitted By :
Faculty Name :_________________ Name :_________________
Designation :_________________ Roll No. :_________________
Section :_________________
Table of Contents
• Vision and Mission Statements of the Institute

• Vision and Mission Statements of the Department

• PEOs, POs, PSOs of the Department

• Course Objective and Outcomes

• List of Experiments

• Index
Department Vision Statement
To be a recognized Department of Computer Science & Engineering that produces versatile computer
engineers, capable of adapting to the changing needs of computer and related industry.

Department Mission Statements


The mission of the Department of Computer Science and Engineering is:

i. To provide broad based quality education with knowledge and attitude to succeed in Computer
Science & Engineering careers.

ii. To prepare students for emerging trends in computer and related industry.

iii. To develop competence in students by providing them skills and aptitude to foster culture of
continuous and lifelong learning.

iv. To develop practicing engineers who investigate research, design, and find workable solutions to
complex engineering problems with awareness & concern for society as well as environment.

Program Educational Objectives (PEOs)


i. The graduates will be efficient leading professionals with knowledge of computer science &
engineering discipline that enables them to pursue higher education and/or successful careers in
various domains.

ii. Graduates will possess capability of designing successful innovative solutions to real life problems
that are technically sound, economically viable and socially acceptable.

iii. Graduates will be competent team leaders, effective communicators and capable of working in
multidisciplinary teams following ethical values.

iv. The graduates will be capable of adapting to new technologies/tools and constantly upgrading their
knowledge and skills with an attitude for lifelong learning
Department Program Outcomes (POs)
The students of Computer Science and Engineering Department will be able:

1. Engineering knowledge: Apply the knowledge of mathematics, science, Computer 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 Computer Science & Engineering sciences.

3. Design/development of solutions: Design solutions for complex Computer Science &


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. Investigation: 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 Computer Science &
Engineering activities with an understanding of the limitations.

6. The Engineering 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 in the field of Computer Science and Engineering.

7. Environment and sustainability: Understand the impact of the professional Computer Science
& 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 Computer Science & 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 Computer Science & 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 Computer
Science & 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.
Department Program Specific Outcomes (PSOs)
The students will be able to:

1. Use algorithms, data structures/management, software design, concepts of programming


languages and computer organization and architecture.

2. Understand the processes that support the delivery and management of information systems
within a specific application environment.

Course Outcomes
*Level of Bloom’s Level to be
*Level of Bloom’s Taxonomy Level to be met
Taxonomy met
L1: Remember 1 L2: Understand 2
L3: Apply 3 L4: Analyze 4
L5: Evaluate 5 L6: Create 6

CO Number Course Outcomes


BCS-553.1 Apply [L3: Application] an Algorithm to solve a computational problem.

BCS-553.2 Analyze [L4: Analysis] an Algorithm to solve a computational problem.


List of Experiments

Sl.
Name of the problems COs
No.
Implementation and Analysis of Linear Search Using recursive function
1 CO2
Implementation and Analysis of Binary Search Using recursive function
Implementation and Analysis of Insertion Sort.
2 Implementation and Analysis of Selection Sort. CO2
Implementation and Analysis of Bubble Sort.
Implementation and Analysis of Merge Sort.
3 CO2
Implementation and Analysis of Quick Sort.
Implementation and Analysis of Heap Sort.
4 Implementation and Analysis of Counting Sort. CO2
Implementation and Analysis of Radix Sort.
5 Implementation of Shell Sort. CO2
Implementation of Activity Selection Problem
6 CO1
Implementation of Knapsack Problem using Greedy Solution
Implement and Analysis of the 0/1 Knapsack problem using Dynamic Programming method
7 CO2
Implementation and Analysis of LCS
Implementation of Kruskal’s algorithm to find MST.
8 CO1
Implementation of Prim’s algorithm to find MST.
Implementation of Warshal’s Algorithm for All Pair Shortest Path.
9 CO1
Implementation of Dijkstra Algorithm for Single Source Shortest Path.
Implementation of N Queen Problem using Backtracking
10 CO1
Implementation of Sum of Subset problem using Backtracking
INDEX
S Lab Experiment Date of Date of Marks Faculty
No Experiment Submission Signature

10
EXPERIMENT 1

Question 1: Implementation and Analysis of Linear Search Using recursive function

Code:

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

int linearSearch(int arr[], int size, int target, int index) {


if (index >= size) {
return -1;
}
if (arr[index] == target) {
return index;
}
return linearSearch(arr, size, target, index + 1);
}

void generateRandomArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
arr[i] = rand() % 10000;
}
}

int main() {
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
int numSizes = sizeof(sizes) / sizeof(sizes[0]);
srand(time(0));
printf("%-15s %-15s\n", "Input Size", "Time (ms)");
printf("-------------------------------\n");
fflush(stdout);

for (int i = 0; i < numSizes; i++) {


int size = sizes[i];
int *arr = (int *)malloc(size * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed for size %d\n", size);
return 1;
}

generateRandomArray(arr, size);
int target = rand() % 10000;

clock_t start = clock();

linearSearch(arr, size, target, 0);


clock_t end = clock();
double time_spent = ((double)(end - start) / CLOCKS_PER_SEC) * 1000;
printf("%-15d %-15.3f\n", size, time_spent);
fflush(stdout);

free(arr);
}
return 0;
}

Output:
Question 2: Implementation and Analysis of Binary Search Using recursive function

Code:

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

int binarySearch(int arr[], int left, int right, int target) {


if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] > target) {
return binarySearch(arr, left, mid - 1, target);
}
return binarySearch(arr, mid + 1, right, target);
}

void generateRandomArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
arr[i] = rand() % 10000;
}
}

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


return (*(int *)a - *(int *)b);
}

int main() {
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
int numSizes = sizeof(sizes) / sizeof(sizes[0]);

srand(time(0));

printf("%-15s %-15s\n", "Input Size", "Time (ms)");


printf("-------------------------------\n");

for (int i = 0; i < numSizes; i++) {


int size = sizes[i];
int *arr = (int *)malloc(size * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed for size %d\n", size);
return 1;
}

generateRandomArray(arr, size);
qsort(arr, size, sizeof(int), compare);
int target = rand() % 10000;

clock_t start = clock();


binarySearch(arr, 0, size - 1, target);
clock_t end = clock();
double time_spent = ((double)(end - start) / CLOCKS_PER_SEC) * 1000;
printf("%-15d %-15.3f\n", size, time_spent);
free(arr);
}
return 0;
}

Output:
EXPERIMENT 2

Question 1: Implementation and Analysis of Insertion Sort.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
insertionSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}

Output:
Question 2: Implementation and Analysis of Selection Sort.

Code:

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

void selectionSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
selectionSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}

Output:
Question 3: Implementation and Analysis of Bubble Sort.

Code:

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

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
bubbleSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}

Output:
EXPERIMENT 3

Question 1: Implementation and Analysis of Merge sort

Code:

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

void merge(int arr[], int l, int m, int r) {


int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) arr[k++] = L[i++];
else arr[k++] = R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
mergeSort(arr, 0, size - 1);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}
Output:
Question 2: Implementation and Analysis of Quick sort

Code:

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

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


int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}

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


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
quickSort(arr, 0, size - 1);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}
Output:
EXPERIMENT 4

Question 1: Implementation and Analysis of Heap sort

Code:

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

void heapify(int arr[], int n, int i) {


int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest]) largest = l;
if (r < n && arr[r] > arr[largest]) largest = r;
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
heapSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) / CLOCKS_PER_SEC);
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}
Output:
Question 2: Implementation and Analysis of Counting sort

Code:

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

void countingSort(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
int *count = (int *)calloc(max + 1, sizeof(int));
int *output = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) count[arr[i]]++;
for (int i = 1; i <= max; i++) count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < n; i++) arr[i] = output[i];
free(count);
free(output);
}
void measureTime(int size) {
int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
countingSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start));
free(arr);
}
int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}

Output:
Question 3 : Implementation and Analysis of Radix sort

Code:

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

int getMax(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
return max;
}

void countSort(int arr[], int n, int exp) {


int *output = (int *)malloc(n * sizeof(int));
int count[10] = {0};
for (int i = 0; i < n; i++) count[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++) count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++) arr[i] = output[i];
free(output);
}

void radixSort(int arr[], int n) {


int m = getMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10) countSort(arr, n, exp);
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
radixSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start));
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}
Output:
EXPERIMENT 5

Question : Implementation of Shell Sort

Code:

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

void shellSort(int arr[], int n) {


for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
}

void measureTime(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) arr[i] = rand() % 10000;
clock_t start = clock();
shellSort(arr, size);
clock_t end = clock();
printf("%d\t%f\n", size, (double)(end - start) );
free(arr);
}

int main() {
srand(time(NULL));
printf("Size\tTime\n");
int sizes[] = {50, 100, 500, 1000, 5000, 10000, 50000, 100000};
for (int i = 0; i < 8; i++) measureTime(sizes[i]);
return 0;
}

Output:
EXPERIMENT 6

Question 1: Implementation of Activity Selection Problem

Code:

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

typedef struct {
int start, finish;
} Activity;

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


return ((Activity *)a)->finish - ((Activity *)b)->finish;
}

void activitySelection(Activity activities[], int n) {


qsort(activities, n, sizeof(Activity), compare);
int i = 0;
printf("Selected activities: (%d, %d)\n", activities[i].start, activities[i].finish);
for (int j = 1; j < n; j++) {
if (activities[j].start >= activities[i].finish) {
printf("(%d, %d)\n", activities[j].start, activities[j].finish);
i = j;
}
}
}

int main() {
Activity activities[] = {{1, 3}, {2, 5}, {4, 6}, {6, 7}, {5, 9}, {8, 9}};
int n = sizeof(activities) / sizeof(activities[0]);
activitySelection(activities, n);
return 0;
}

Output:
Question 2: Implementation of Knapsack Problem Using Greedy Solution

Code:

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

typedef struct {
int weight, value;
double ratio;
} Item;

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


return ((Item *)b)->ratio - ((Item *)a)->ratio;
}

double knapsack(Item items[], int n, int capacity) {


qsort(items, n, sizeof(Item), compare);
double totalValue = 0.0;
for (int i = 0; i < n; i++) {
if (capacity >= items[i].weight) {
capacity -= items[i].weight;
totalValue += items[i].value;
} else {
totalValue += items[i].value * ((double)capacity / items[i].weight);
break;
}
}
return totalValue;
}

int main() {
Item items[] = {{10, 60}, {20, 100}, {30, 120}};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 50;
printf("Maximum value in Knapsack = %.2f\n", knapsack(items, n, capacity));
return 0;
}

Output:
EXPERIMENT 7

Question 1: Implement and Analysis of the 0/1 Knapsack problem using Dynamic Programming
Method Implement and Analysis of LCS

Code:

#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int knapsack(int W, int wt[], int val[], int n) {
int dp[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (wt[i - 1] <= w)
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
printf("%d\n", knapsack(W, wt, val, n));
return 0;
}

Output:
Question 2: Implementation and Analysis of LCS

Code:

#include <stdio.h>
#include <string.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int lcs(char *X, char *Y, int m, int n) {
int dp[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
int main() {
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
int m = strlen(X);
int n = strlen(Y);
printf("%d\n", lcs(X, Y, m, n));
return 0;
}

Output:
EXPERIMENT 8

Question 1: Implementation of Kruskal’s algorithm to find MST

Code:

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

typedef struct {
int u, v, weight;
} Edge;

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


return ((Edge *)a)->weight - ((Edge *)b)->weight;
}

int find(int parent[], int i) {


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

void unionSet(int parent[], int rank[], int x, int y) {


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

void kruskal(Edge edges[], int V, int E) {


qsort(edges, E, sizeof(Edge), compare);
int parent[V], rank[V];
for (int v = 0; v < V; v++) {
parent[v] = v;
rank[v] = 0;
}
int e = 0, i = 0;
while (e < V - 1 && i < E) {
Edge next_edge = edges[i++];
int x = find(parent, next_edge.u);
int y = find(parent, next_edge.v);
if (x != y) {
printf("Edge %d-%d with weight %d\n", next_edge.u, next_edge.v, next_edge.weight);
unionSet(parent, rank, x, y);
e++;
}
}
}
int main() {
int V = 4, E = 5;
Edge edges[] = {{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};
kruskal(edges, V, E);
return 0;
}

Output:
Question 2: Implementation of Prim’s algorithm to find MST

Code:

#include <stdio.h>
#include <limits.h>
#include <stdbool.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]) {


for (int i = 1; i < V; i++)
printf("Edge %d-%d with weight %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 9

Question 1: Implementation of Warshal’s Algorithm for All Pair Shortest Path.

Code:

#include <stdio.h>

#define V 4

void printSolution(int dist[][V]) {


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == 10000)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

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


int dist[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (int k = 0; k < V; k++)
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
printSolution(dist);
}

int main() {
int graph[V][V] = {{0, 5, 10000, 10},
{10000, 0, 3, 10000},
{10000, 10000, 0, 1},
{10000, 10000, 10000, 0}};
floydWarshall(graph);
return 0;
}

Output:
Question 2: Implementation of Dijkstra’s Algorithm for Single Source Shortest Path

Code:

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

#define V 9

int minDistance(int dist[], bool sptSet[]) {


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

void printSolution(int dist[]) {


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

void dijkstra(int graph[V][V], int src) {


int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; 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];
}
printSolution(dist);
}

int main() {
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, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
dijkstra(graph, 0);
return 0;
}
Output:
EXPERIMENT 10

Question 1: Implementation of N Queen Problem using Backtracking.

Code:

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

#define N 4

void printSolution(int board[N][N]) {


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

bool isSafe(int board[N][N], int row, int col) {


for (int i = 0; i < col; i++)
if (board[row][i])
return false;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (int i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}

bool solveNQUtil(int board[N][N], int col) {


if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}

bool solveNQ() {
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}

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

Output:
Question 2: Implementation of Sum of Subset Problem using Backtracking

Code:

#include <stdio.h>

void printSubset(int subset[], int size) {


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

void subsetSum(int set[], int subset[], int n, int subsetSize, int total, int nodeCount, int sum) {
if (total == sum) {
printSubset(subset, subsetSize);
subsetSum(set, subset, n, subsetSize - 1, total - set[nodeCount], nodeCount + 1, sum);
return;
} else {
for (int i = nodeCount; i < n; i++) {
subset[subsetSize] = set[i];
subsetSum(set, subset, n, subsetSize + 1, total + set[i], i + 1, sum);
}
}
}

void findSubsets(int set[], int size, int sum) {


int *subset = (int *)malloc(size * sizeof(int));
subsetSum(set, subset, size, 0, 0, 0, sum);
free(subset);
}

int main() {
int set[] = {10, 7, 5, 18, 12, 20, 15};
int sum = 35;
int size = sizeof(set) / sizeof(set[0]);
findSubsets(set, size, sum);
return 0;
}

Output:

You might also like