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

BCSL404 ADA Lab Programs

Uploaded by

rashmi gs
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)
21 views

BCSL404 ADA Lab Programs

Uploaded by

rashmi gs
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/ 46

Analysis & Design of Algorithms Lab (BCSL404)

INDEX

S.NO EXPERIMENTS

Introductory Programs

Design and implement C/C++ Program to sort a given set of n integer elements using Selec on
Sort method and compute its me complexity. Run the program for varied values of n> 5000 and
1.
record the me taken to sort. Plot a graph of the me taken versus n. The elements can be read
from a file or can be generated using the random number generator. (9th prog)

Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort
2.
method and compute its me complexity. Run the program for varied values of n> 5000 and
record the me taken to sort. Plot a graph of the me taken versus n. The elements can be read
from a file or can be generated using the random number generator. (10th prog)
Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sort
method and compute its me complexity. Run the program for varied values of n> 5000, and
3.
record the me taken to sort. Plot a graph of the me taken versus n. The elements can be read
from a file or can be generated using the random number generator (11th prog)

4.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
5.
undirected graph using Prim's algorithm
a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's
6.
algorithm. b. Warshall’s Algorithm
Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
7.
connected graph to other ver ces using Dijkstra's algorithm.
Design and implement C/C++ Program to obtain the Topological ordering of ver ces in a given
8.
digraph.

9. Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method
Design and implement C/C++ Program to solve discrete Knapsack and con nuous Knapsack
10.
problems using greedy approxima on method
Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n
11.
posi ve integers whose sum is equal to a given posi ve integer d.
12 Design and implement C/C++ Program for N Queen's problem using Backtracking
SAMPLE VIVA QUESTIONS AND ANSWERS

1
Analysis & Design of Algorithms Lab (BCSL404)

Introductory Programs:
Euclid’s algorithm for compu ng GCD(m,n)

Program:
#include <stdio.h>

int euclid(int m, int n) {


int r;
while (n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}

int main() {
int m, n;
prin ("Enter two non-nega ve integers m and n: ");
scanf("%d %d", &m, &n);
// Ensure both m and n are non-nega ve
if (m < 0 || n < 0) {
prin ("Error: Both integers must be non-nega ve.\n");
} else {
int result = euclid(m, n);
prin ("GCD of %d and %d is: %d\n", m, n, result);
}
return 0;
}

Program:

2
Analysis & Design of Algorithms Lab (BCSL404)

#include <stdio.h>

int consecu veIntegerGCD(int m, int n) {


int t = (m < n) ? m : n; // Step 1: Assign the value of min{m, n} to t
while (t > 0) {
// Step 2: Divide m by t
if (m % t == 0) {
// Step 3: If remainder is 0, divide n by t
if (n % t == 0) {
return t; // Return t as the GCD
}
}
// Step 4: Decrease the value of t by 1
t--;
}
return 0; // If no common divisor found, return 0
}

int main() {
int m, n;
prin ("Enter two non-nega ve integers m and n: ");
scanf("%d %d", &m, &n);
// Ensure both m and n are non-nega ve
if (m < 0 || n < 0) {
prin ("Error: Both integers must be non-nega ve.\n");
} else {
int result = consecu veIntegerGCD(m, n);
prin ("GCD of %d and %d is: %d\n", m, n, result);
}
return 0;
}

3
Analysis & Design of Algorithms Lab (BCSL404)

Lab Programs:

1. Design and implement C/C++ Program to sort a given set of n integer elements using Selection 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 n. The elements can be read from a file
or can be generated using the random number generator. (9 th prog)

Aim: Sort a given set of elements using Selection sort and determine the time required to sort elements.
Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a
graph of the time taken versus n.

Definition: selection sort is a sorting routine that scans a list of items repeatedly and, on each pass, selects the
item with the lowest value and places it in its final position. It is based on brute force approach.

Brute force is a straightforward approach to solving a problem, usually directly based on the problem
statement and definitions of the concepts involved. Selection Sort uses Brute Force Approach.

 Algorithm start by scanning the entire given list to find its smallest element and exchange it with the
first element, putting the smallest element in its final position in the sorted list (outer loop).
 ith pass through the list, i.e. from 0 to n − 2, the algorithm searches for the smallest item among the
last n − i elements and swaps it with Ai:
 After n − 1 passes, the list is sorted.

Eg:
89 45 68 90 29 34 17
17 45 68 90 29 34 89
17 29 68 90 45 34 89
17 29 34 90 45 68 89
17 29 34 45 90 68 89
17 29 34 45 68 90 89
17 29 34 45 68 89 90

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

4
Analysis & Design of Algorithms Lab (BCSL404)

#include <time.h>
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap arr[i] and arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[100000];

// Generating random numbers as elements


srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000;
printf("%d ", arr[i]);
}
printf("\n");
// Perform Selection Sort
clock_t start = clock();
selectionSort(arr, n);
clock_t end = clock();

// Calculate time taken in milliseconds


double total = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;
// Print sorted array
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\nTotal time taken: %.2f ms\n", total);
return 0;
}
Output:

5
Analysis & Design of Algorithms Lab (BCSL404)

2. Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort
method and compute its me complexity. Run the program for varied values of n> 5000 and record
the me taken to sort. Plot a graph of the me taken versus n. The elements can be read from a file
or can be generated using the random number generator. (10th prog)

Aim: The aim of this program is to sort ‘n’ randomly generated elements using Quick sort and Plotting the
graph of the time taken to sort n elements versus n.

Definition: Quick sort is based on the Divide and conquer approach. Quick sort divides array according to their
value. Partition is the situation where all the elements before some position s are smaller than or equal to A[s]
and all the elements after position s are greater than or equal to A[s].

Quick-sort algorithm works as follows


Algorithm rearranges elements of a given array A[0---n-1] to achieve its par on, where all the elements
before some posi on s are smaller than or equal to A[s] and all the elements a er the posi on s are greater
than or equal to A[s]:

Code:
#include <stdio.h>
#include <stdlib.h>
#include < me.h>

6
Analysis & Design of Algorithms Lab (BCSL404)

// Func on to swap two elements in an array


void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Func on to par on the array


int par on(int arr[], int low, int high) {
int pivot = arr[low];
int i = low, j = high + 1, temp;
while (1) {
do {
i++;
} while (arr[i] < pivot && i <= high);

do {
j--;
} while (arr[j] > pivot);

if (i >= j)
break;

// Swap arr[i] and arr[j]


swap(&arr[i], &arr[j]);
}

// Swap arr[low] and arr[j]


swap(&arr[low], &arr[j]);

return j;
}

// Func on to perform Quick Sort


void quickSort(int arr[], int low, int high) {
if (low < high) {
int k = par on(arr, low, high);
quickSort(arr, low, k - 1);
quickSort(arr, k + 1, high);
}
}

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

7
Analysis & Design of Algorithms Lab (BCSL404)

int arr[n];
srand( me(NULL));
prin ("Array Generated: ");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000;
prin ("%d ", arr[i]);
}
prin ("\n");

clock_t start = clock();


quickSort(arr, 0, n - 1);
clock_t end = clock();

prin ("Sorted Array: ");


for (int i = 0; i < n; i++)
prin ("%d ", arr[i]);
prin ("\n");

// Calculate me taken in milliseconds


double total = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;
prin ("\nTotal me taken: %.2f ms\n", total);
return 0;
}

Output:

8
Analysis & Design of Algorithms Lab (BCSL404)

3. Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sort
method and compute its me complexity. Run the program for varied values of n> 5000, and record
the me taken to sort. Plot a graph of the me taken versus n. The elements can be read from a file
or can be generated using the random number generator (11th prog)

Aim:

The aim of this program is to sort ‘n’ randomly generated elements using Merge sort and Plotting the graph
of the time taken to sort n elements versus n.
Definition: Merge sort is a sort algorithm based on divide and conquer technique. It divides the array element
based on the position in the array. The concept is that we first break the list into two smaller lists of roughly
the same size, and then use merge sort recursively on the subproblems, until they cannot subdivide anymore.
Then, we can merge by stepping through the lists in linear time. Its time efficiency is Θ(n log n).

 Merge sort is a perfect example of the divide-and-conquer technique.


 It sorts a given array A[0..n − 1] by dividing it into two halves A[0..n/2 − 1] and A[n/2..n − 1], and sort
each of them recursively,
 Then merging the two smaller sorted arrays into a single sorted one.
The merging of two sorted arrays can be done as follows.
1. Two array indices (ex: i and j) are ini alized to point to the first elements of the arrays being merged.
2. The elements pointed by i and j are compared, and the smaller of them is added to a new array; a er
that, the index of the smaller element is incremented to point to its immediate successor in the array
it was copied from.
3. This opera on is repeated un l one of the two sub-arrays is exhausted, and then the remaining
elements of the other array are copied to the end of the new array.

9
Analysis & Design of Algorithms Lab (BCSL404)

Code:
#include <stdio.h>
#include <stdlib.h>
#include < me.h>

// Func on to merge two subarrays


void merge(int arr[], int low, int mid, int high) {
int n1 = mid - low + 1;
int n2 = high - mid;
int L[n1], R[n2];

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


L[i] = arr[low + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

int i = 0, j = 0, k = low;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

// Func on to perform Merge Sort


void mergeSort(int arr[], int low, int high) {
if (low < high) {
int mid = low + (high - low) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}

10
Analysis & Design of Algorithms Lab (BCSL404)

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

int arr[n];
srand( me(NULL));
prin ("Array Generated: ");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000;
prin ("%d ", arr[i]);
}
prin ("\n");

clock_t start = clock();


mergeSort(arr, 0, n - 1);
clock_t end = clock();

prin ("Sorted Array: ");


for (int i = 0; i < n; i++)
prin ("%d ", arr[i]);
prin ("\n");

double total = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;


prin ("Time taken: %.2f ms\n", total);

return 0;
}

Output:

11
Analysis & Design of Algorithms Lab (BCSL404)

4. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm.

Aim : To apply Kruskal's Algorithm for computing the minimum spanning tree is directly based on the generic
MST algorithm. It builds the MST in forest.

Defini on: Kruskal’s algorithm is an algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. This means 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. If the graph is not connected, then it
finds a minimum spanning forest .It is an example of a greedy algorithm.

Start with an empty set A, and select at every stage the shortest edge that has not been chosen or rejected,
regardless of where this edge is situated in graph.

 Initially, each vertex is in its own tree in forest.


 Then, algorithm consider each edge in turn, order by increasing weight.

 If an edge (u, v) connects two different trees, then (u, v) is added to the set of edges of the MST, and
two trees connected by an edge (u, v) are merged into a single tree.

 On the other hand, if an edge (u, v) connects two vertices in the same tree, then edge (u, v) is
discarded.

Code:
#include <stdio.h>
#define MAX_VERTICES 100

void kruskalApproach(int c[MAX_VERTICES][MAX_VERTICES], int n) {


int i, j, e = 0, cost = 0, u = 0, v = 0, a = 0, b = 0, min;
int p[MAX_VERTICES];
for (i = 0; i < n; i++)
p[i] = -1;

12
Analysis & Design of Algorithms Lab (BCSL404)

while (e != n - 1) {
min = 999;
//Selec ng edge from a given input graph in ascending order.
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (c[i][j] < min) {
min = c[i][j];
a = u = i;
b = v = j;
}
}
}

//Checking whether the selected edge creates cycle or not.


while (p[u] != -1)
u = p[u];
while (p[v] != -1)
v = p[v];

if (u != v) {
prin ("%d --> %d = %d\n", a, b, min);
p[v] = u;
e = e + 1;
cost = cost + min;
}
c[a][b] = c[b][a] = 999;
}
prin ("\nMinimum cost of a spanning tree is %d units\n", cost);
}

int main() {
int i, j, n;
prin ("Enter the number of ver ces: ");
scanf("%d", &n);
int c[MAX_VERTICES][MAX_VERTICES];

prin ("Enter the weighted graph in form of adjacency matrix:\n");


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
scanf("%d", &c[i][j]);
}

prin ("\nMatrix:\n");
for (i = 0; i < n; i++) {

13
Analysis & Design of Algorithms Lab (BCSL404)

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


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

kruskalApproach(c, n);
return 0;
}

Output:

14
Analysis & Design of Algorithms Lab (BCSL404)

5. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm

Aim:To find minimum spanning tree of a given graph using prim’s algorithm

Defini on: Prim’s is an algorithm that finds a minimum spanning tree for a connected weighted undirected
graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total
weight of all edges in the tree is minimized. Prim’s algorithm is an example of a greedy algorithm.

15
Analysis & Design of Algorithms Lab (BCSL404)

Code:
#include <stdio.h>

#define MAX_VERTICES 100


#define INF 999

int primApproach(int a[MAX_VERTICES][MAX_VERTICES], int n, int source) {


int s[MAX_VERTICES] = {0};
int d[MAX_VERTICES];
int u, v, min, sum = 0;

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


d[i] = a[source][i];
}
s[source] = 1;

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


min = INF;
for (int j = 0; j < n; j++) {
if (s[j] == 0 && d[j] < min) {
min = d[j];
u = j;
}
}
s[u] = 1;
sum += d[u];

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


if (s[v] == 0 && d[v] > a[u][v]) {
d[v] = a[u][v];
}

16
Analysis & Design of Algorithms Lab (BCSL404)

}
}
return sum;
}

int main() {
int i, j, n;
prin ("Enter the number of ver ces: ");
scanf("%d", &n);
int a[MAX_VERTICES][MAX_VERTICES];

prin ("Enter the weighted graph in form of adjacency matrix:\n");


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

prin ("\nMatrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
prin ("%d\t", a[i][j]);
prin ("\n");
}

int source;
prin ("\nEnter the source vertex: ");
scanf("%d", &source);

int minimumCost = primApproach(a, n, source);


prin ("Minimum cost of the spanning tree is %d units\n", minimumCost);

return 0;
}

Output:

17
Analysis & Design of Algorithms Lab (BCSL404)

18
Analysis & Design of Algorithms Lab (BCSL404)

6. a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's
algorithm.

Code:
#include <stdio.h>

#define MAX_VERTICES 100


#define INF 999

int min(int a, int b) {


return (a < b) ? a : b;
}

void floydAlgorithm(int a[MAX_VERTICES][MAX_VERTICES], int n) {


int d[MAX_VERTICES][MAX_VERTICES];

// Copying the input graph to the distance matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = a[i][j];
}
}

// Applying Floyd's algorithm


for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (d[i][k] != INF && d[k][j] != INF && d[i][j] > d[i][k] + d[k][j]) {
d[i][j] = d[i][k] + d[k][j];

19
Analysis & Design of Algorithms Lab (BCSL404)

}
}
}
}

// Prin ng the shortest distances


prin ("\nShortest informa on:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d\t", d[i][j]);
}
prin ("\n");
}
}

int main() {
int n;
prin ("Enter the number of ver ces: ");
scanf("%d", &n);

int a[MAX_VERTICES][MAX_VERTICES];
prin ("Enter the weighted graph in form of adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
if (a[i][j] == 0 && i != j) {
a[i][j] = INF;
}
}
}

prin ("\nMatrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d\t", a[i][j]);
}
prin ("\n");
}

floydAlgorithm(a, n);

return 0;
}

Output:

20
Analysis & Design of Algorithms Lab (BCSL404)

b. Design and implement C/C++ Program to find the transi ve closure using Warshal's algorithm.

Code:
#include <stdio.h>

#define MAX_VERTICES 100

void warshallAlgorithm(int a[MAX_VERTICES][MAX_VERTICES], int n) {


int transi veClosure[MAX_VERTICES][MAX_VERTICES];

// Ini alize transi ve closure matrix with the given adjacency matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
transi veClosure[i][j] = a[i][j];
}
}

// Applying Warshall's algorithm to find transi ve closure


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

21
Analysis & Design of Algorithms Lab (BCSL404)

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


for (int j = 0; j < n; j++) {
if (transi veClosure[i][k] && transi veClosure[k][j])
transi veClosure[i][j] = 1;
}
}
}

// Prin ng the transi ve closure matrix


prin ("\nTransi ve Closure:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d\t", transi veClosure[i][j]);
}
prin ("\n");
}
}

int main() {
int n;
prin ("Enter the number of ver ces: ");
scanf("%d", &n);

int a[MAX_VERTICES][MAX_VERTICES];
prin ("Enter the directed graph in form of adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}

prin ("\nMatrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d\t", a[i][j]);
}
prin ("\n");
}

warshallAlgorithm(a, n);

return 0;
}

Output:

22
Analysis & Design of Algorithms Lab (BCSL404)

23
Analysis & Design of Algorithms Lab (BCSL404)

7. Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
connected graph to other ver ces using Dijkstra's algorithm.

Aim: To find shortest path using Dijikstra’s algorithm.


Definition: Dijikstra’s algorithm -For a given source vertex(node) in the graph, the algorithm finds the path
with lowest cost between that vertex and every other vertex. It can also be used for finding cost of shortest
paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to
the destination vertex has been determined.

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

#define MAX_VERTICES 100


#define INF 999

void dijkstraAlgorithm(int a[MAX_VERTICES][MAX_VERTICES], int n, int source) {


int d[MAX_VERTICES];
bool s[MAX_VERTICES];

// Ini alize distance array and visited array


for (int i = 0; i < n; i++) {
d[i] = a[source][i];
s[i] = false;
}
s[source] = true;

24
Analysis & Design of Algorithms Lab (BCSL404)

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


int u, min = INF;

// Find the vertex with the minimum distance from the source vertex
for (int v = 0; v < n; v++) {
if (!s[v] && d[v] < min) {
min = d[v];
u = v;
}
}

// Mark the selected vertex as visited


s[u] = true;

// Update distance values of adjacent ver ces of the selected vertex


for (int v = 0; v < n; v++) {
if (!s[v] && a[u][v] && d[u] != INF && d[u] + a[u][v] < d[v]) {
d[v] = d[u] + a[u][v];
}
}
}

// Print shortest paths from the source vertex


prin ("\nShortest paths:\n");
for (int i = 0; i < n; i++) {
prin ("%d --> %d = %d\n", source, i, d[i]);
}
}

int main() {
int n;
prin ("Enter the number of ver ces: ");
scanf("%d", &n);

int a[MAX_VERTICES][MAX_VERTICES];
prin ("Enter the weighted graph in form of adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}

prin ("\nMatrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d\t", a[i][j]);

25
Analysis & Design of Algorithms Lab (BCSL404)

}
prin ("\n");
}

int source;
prin ("\nEnter the source vertex: ");
scanf("%d", &source);

dijkstraAlgorithm(a, n, source);

return 0;
}

Output:

26
Analysis & Design of Algorithms Lab (BCSL404)

8. Design and implement C/C++ Program to obtain the Topological ordering of ver ces in a given
digraph.

Aim: To find topological ordering of given graph


Definition: Topological ordering that for every edge in the graph, the vertex where the edge starts is listed
before the edge where the edge ends.

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

#define MAX_VERTICES 100

// Adjacency list node


struct Node {
int vertex;
struct Node* next;
};

// Adjacency list representa on of a graph


struct Graph {
int numVer ces;
struct Node** adjLists;
int* visited;
};

// Create a new node


struct Node* createNode(int v) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Create a graph with given number of ver ces


struct Graph* createGraph(int ver ces) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVer ces = ver ces;

graph->adjLists = calloc(ver ces, sizeof(struct Node*));


graph->visited = calloc(ver ces, sizeof(int));

return graph;
}

// Add an edge to the graph

27
Analysis & Design of Algorithms Lab (BCSL404)

void addEdge(struct Graph* graph, int src, int dest) {


struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}

// Depth-First Search recursive func on


void DFS(struct Graph* graph, int vertex, int* stack, int* index) {
graph->visited[vertex] = 1;

struct Node* adjList = graph->adjLists[vertex];


while (adjList != NULL) {
int connectedVertex = adjList->vertex;
if (!graph->visited[connectedVertex]) {
DFS(graph, connectedVertex, stack, index);
}
adjList = adjList->next;
}

stack[(*index)++] = vertex;
}

// Topological sor ng func on


void topologicalSort(struct Graph* graph) {
int stack[MAX_VERTICES], index = 0;

for (int i = 0; i < graph->numVer ces; i++) {


if (!graph->visited[i]) {
DFS(graph, i, stack, &index);
}
}

prin ("Topological ordering of ver ces: ");


while (index--) {
prin ("%d ", stack[index]);
}
prin ("\n");
}

int main() {
int numVer ces, numEdges;
prin ("Enter the number of ver ces: ");
scanf("%d", &numVer ces);
prin ("Enter the number of edges: ");
scanf("%d", &numEdges);

28
Analysis & Design of Algorithms Lab (BCSL404)

struct Graph* graph = createGraph(numVer ces);

prin ("Enter the edges (source des na on):\n");


for (int i = 0, src, dest; i < numEdges; i++) {
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}

topologicalSort(graph);

return 0;
}
Output:

29
Analysis & Design of Algorithms Lab (BCSL404)

9. Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic Programming
method

Aim: To implement 0/1 Knapsack problem using Dynamic programming

Definition: using Dynamic programming


It gives us a way to design custom algorithms which systematically search all possibilities (thus guaranteeing
correctness) while storing results to avoid recomputing (thus providing efficiency).
We are given a set of n items from which we are to select some number of items to be carried in a
knapsack(BAG). Each item has both a weight and a profit. The objective is to choose the set of items that fits in
the knapsack and maximizes the profit.
Given a knapsack with maximum capacity W, and a set S consisting of n items , Each item i has some weight wi
and benefit value bi (all wi , bi and W are integer values)
Problem: How to pack the knapsack to achieve maximum total value of packed items?

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

#define MAX_ITEMS 50
#define max(a, b) ((a > b) ? a : b)

void knapsack(int n, int m, int w[], int p[]) {


int v[MAX_ITEMS + 1][m + 1];
for (int i = 0; i <= n; i++) {

30
Analysis & Design of Algorithms Lab (BCSL404)

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


if (i == 0 || j == 0) {
v[i][j] = 0;
} else if (j < w[i - 1]) {
v[i][j] = v[i - 1][j];
} else {
v[i][j] = max(v[i - 1][j], v[i - 1][j - w[i - 1]] + p[i - 1]);
}
}
}
prin ("Solu on Matrix:\n");
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
prin ("%d\t", v[i][j]);
}
prin ("\n");
}
prin ("Solu on: %d units\n", v[n][m]);
}

int main() {
int n, m;
prin ("Enter the number of items: ");
scanf("%d", &n);
int w[MAX_ITEMS], p[MAX_ITEMS];
prin ("Enter the capacity of knapsack: ");
scanf("%d", &m);
prin ("Enter the weight of items:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &w[i]);
}
prin ("Enter the profit of items:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &p[i]);
}
knapsack(n, m, w, p);
return 0;
}

Output:

31
Analysis & Design of Algorithms Lab (BCSL404)

32
Analysis & Design of Algorithms Lab (BCSL404)

10. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method

This program first calculates the profit-to-weight ra o for each item, then sorts the items based on this ra o in
non-increasing order. It then fills the knapsack greedily by selec ng items with the highest ra o un l the
knapsack is full. If there's space le in the knapsack a er selec ng whole items, it adds frac onal parts of the
next item. Finally, it prints the op mal solu on and the solu on vector.

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

#define MAX_ITEMS 50

// Structure to represent an item


typedef struct {
int weight;
int profit;
float ratio; // Ratio of profit to weight
} Item;

// Function to swap two items


void swap(Item* a, Item* b) {
Item temp = *a;
*a = *b;
*b = temp;
}
// Greedy approach for discrete Knapsack
int discreteKnapsack(int n, int capacity, Item items[]) {
int totalProfit = 0;
for (int i = 0; i < n; i++) {
if (capacity <= 0) break;
if (items[i].weight <= capacity) {
totalProfit += items[i].profit;
capacity -= items[i].weight;
} else {
totalProfit += (int)(items[i].ratio * capacity);
capacity = 0;
}

33
Analysis & Design of Algorithms Lab (BCSL404)

}
return totalProfit;
}

// Greedy approach for continuous Knapsack


float continuousKnapsack(int n, int capacity, Item items[]) {
float totalProfit = 0.0;
for (int i = 0; i < n; i++) {
if (capacity <= 0) break;
if (items[i].weight <= capacity) {
totalProfit += items[i].profit;
capacity -= items[i].weight;
} else {
totalProfit += items[i].ratio * capacity;
capacity = 0;
}
}
return totalProfit;
}

int main() {
int n, capacity;
printf("Enter the number of items: ");
scanf("%d", &n);
printf("Enter the capacity of knapsack: ");
scanf("%d", &capacity);

Item items[MAX_ITEMS];
printf("Enter the weight and profit of each item:\n");
for (int i = 0; i < n; i++) {
scanf("%d %d", &items[i].weight, &items[i].profit);
items[i].ratio = (float)items[i].profit / items[i].weight;
}

// Sort items based on profit-to-weight ratio (descending order)


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (items[j].ratio < items[j + 1].ratio) {
swap(&items[j], &items[j + 1]);
}
}
}

// Discrete Knapsack
int discreteProfit = discreteKnapsack(n, capacity, items);
printf("Discrete Knapsack - Maximum Profit: %d\n", discreteProfit);

// Continuous Knapsack
float continuousProfit = continuousKnapsack(n, capacity, items);
printf("Continuous Knapsack - Maximum Profit: %.2f\n", continuousProfit);

34
Analysis & Design of Algorithms Lab (BCSL404)

return 0;
}

Output:

35
Analysis & Design of Algorithms Lab (BCSL404)

11. Design and implement C/C++ Program 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.

AIM: An instance of the Subset Sum problem is a pair (S, t), where S = {x1, x2, ..., xn} is a set of positive
integers and t (the target) is a positive integer. The decision problem asks for a subset of S whose sum is as
large as possible, but not larger than t.

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

#define MAX_SIZE 100

// Function to find subsets with the given sum


void findSubsets(int set[], int n, int d, int subset[], int size, int sum) {
if (sum == d) { // If sum is equal to d, print the subset
printf("Subset with sum %d found: ", d);
for (int i = 0; i < size; i++) {
printf("%d ", subset[i]);
}
printf("\n");
return;
}

if (n == 0 || sum > d) // If no more elements or sum exceeds d, return


return;

// Include the current element and recursively check for sum


subset[size] = set[0];
findSubsets(set + 1, n - 1, d, subset, size + 1, sum + set[0]);

// Exclude the current element and recursively check for sum


findSubsets(set + 1, n - 1, d, subset, size, sum);
}

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

int set[MAX_SIZE];
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &set[i]);

printf("Enter the sum to be obtained: ");


scanf("%d", &d);
int subset[MAX_SIZE] = {0}; // Initialize subset array with 0s
findSubsets(set, n, d, subset, 0, 0);
return 0;

36
Analysis & Design of Algorithms Lab (BCSL404)

Output:

37
Analysis & Design of Algorithms Lab (BCSL404)

12. Design and implement C/C++ Program for N Queen's problem using Backtracking

Aim: To implement N Queens Problem using Back Tracking


Definition:
The object is to place queens on a chess board in such as way as no queen can capture another one in
a single move
Recall that a queen can move horz, vert, or diagonally an infinite distance
This implies that no two queens can be on the same row, col, or diagonal
We usually want to know how many different placements there are
Using Backtracking Techniques

For only one solu on:


Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// Func on to print the board


void printSolu on(int board[], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i] == j) {
prin ("Q ");
} else {
prin (". ");
}
}
prin ("\n");
}
prin ("\n");
}

// Func on to check if a queen can be placed safely at board[row][col]


bool isSafe(int board[], int row, int col) {
for (int i = 0; i < row; i++) {
// Check if there's a queen in the same column or diagonal
if (board[i] == col || abs(row - i) == abs(col - board[i])) {
return false;
}
}
return true;
}

// Recursive func on to solve N Queens problem


bool solveNQueensU l(int board[], int row, int N) {
if (row >= N) {
// All queens are successfully placed

38
Analysis & Design of Algorithms Lab (BCSL404)

printSolu on(board, N);


return true;
}

// Try placing queen in each column of current row


for (int col = 0; col < N; col++) {
if (isSafe(board, row, col)) {
// Place queen at this posi on
board[row] = col;

// Recur to place rest of the queens


if (solveNQueensU l(board, row + 1, N)) {
return true;
}

// Backtrack if placing queen at this posi on doesn't lead to a solu on


board[row] = -1;
}
}

// If queen can't be placed in any column of this row, return false


return false;
}

// Func on to solve N Queens problem


void solveNQueens(int N) {
int *board = (int *)malloc(N * sizeof(int));
if (board == NULL) {
prin ("Memory alloca on failed!\n");
return;
}

// Ini alize board with no queens placed (-1 represents empty cell)
for (int i = 0; i < N; i++) {
board[i] = -1;
}
solveNQueensU l(board, 0, N);

free(board);
}

int main() {
int N;
prin ("Enter the number of queens (N): ");
scanf("%d", &N);
if (N <= 0) {

39
Analysis & Design of Algorithms Lab (BCSL404)

prin ("Invalid input! Please enter a posi ve integer.\n");


return 1;
}
solveNQueens(N);
return 0;
}

Output:

40
Analysis & Design of Algorithms Lab (BCSL404)

All Possible solu on:


Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

void printSolu on(int board[], int N) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
prin (board[i] == j ? "Q " : ". ");
}
prin ("\n");
}
prin ("\n");
}

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


for (int i = 0; i < row; i++) {
if (board[i] == col || abs(row - i) == abs(col - board[i])) {
return false;
}
}
return true;
}

bool solveNQueensU l(int board[], int row, int N) {


if (row >= N) {
printSolu on(board, N);
return true;
}

bool foundSolu on = false;

for (int col = 0; col < N; col++) {


if (isSafe(board, row, col)) {
board[row] = col;
foundSolu on |= solveNQueensU l(board, row + 1, N);
board[row] = -1;
}
}

return foundSolu on;


}

void solveNQueens(int N) {

41
Analysis & Design of Algorithms Lab (BCSL404)

int board[N];
for (int i = 0; i < N; i++) {
board[i] = -1;
}
if (!solveNQueensU l(board, 0, N)) {
prin ("No solu on exists for N = %d.\n", N);
}
}

int main() {
int N;
prin ("Enter the number of queens (N): ");
scanf("%d", &N);
if (N <= 0) {
prin ("Invalid input! Please enter a posi ve integer.\n");
return 1;
}
solveNQueens(N);
return 0;
}
Output:

42
Analysis & Design of Algorithms Lab (BCSL404)

Sample Viva Ques ons and Answers

1) Explain what is an algorithm in computing?

An algorithm is a well-defined computational procedure that take some value as input and generate some
value as output. In simple words, it’s a sequence of computational steps that converts input into the output.

2) Explain what is time complexity of Algorithm?

Time complexity of an algorithm indicates the total time needed by the program to run to completion. It is
usually expressed by using the big O notation.

3) The main measure for efficiency algorithm are-Time and space


4. The me complexity of following code:
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
} Ans O(n*n)

5) What does the algorithmic analysis count?

6) The number of arithmetic and the operations that are required to run the program

7) Examples of O(1) algorithms are______________


A Multiplying two numbers.
B assigning some value to a variable
C displaying some integer on console

8) Examples of O(n2) algorithms are______________.


A Adding of two Matrices
B Initializing all elements of matrix by zero

9) The complexity of three algorithms is given as: O(n), O(n2) and O(n3). Which should execute slowest for
large value of n?
All will execute in same time.

10) In quick sort, the number of partitions into which the file of size n is divided by a selected record is 2.
The three factors contributing to the sort efficiency considerations are the efficiency in coding, machine run
time and the space requirement for running the procedure.

11) How many passes are required to sort a file of size n by bubble sort method?
N-1

12) How many number of comparisons are required in insertion sort to sort a file if the file is sorted in
reverse order?
A. N2

43
Analysis & Design of Algorithms Lab (BCSL404)

13) How many number of comparisons are required in insertion sort to sort a file if the file is already sorted?
N-1
14) In quick sort, the number of partitions into which the file of size n is divided by a selected record is 2

15) The worst-case time complexity of Quick Sort is________.O(n2)

16)The worst-case time complexity of Bubble Sort is________.O(n2)

17) The worst-case time complexity of Merge Sort is________.O(n log n)

18)The algorithm like Quick sort does not require extra memory for carrying out the sorting procedure. This
technique is called __________.in-place

19)Which of the following sorting procedures is the slowest?


A. Quick sort
B. Heap sort
C. Shell sort
D. Bubble sort

20) The time factor when determining the efficiency of algorithm is measured by Counting the number of
key operations

21)The concept of order Big O is important because


A. It can be used to decide the best algorithm that solves a given problem

22) The running time of insertion sort is


A.O(n^2)

23) A sort which compares adjacent elements in a list and switches where necessary is ____.
A. insertion sort

24) The correct order of the efficiency of the following sorting algorithms according to their overall running
time comparison is
bubble>selection>insertion

25) The total number of comparisons made in quick sort for sorting a file of size n, is
A. O(n log n)

26)Quick sort efficiency can be improved by adopting


A. non-recursive method

27)For the improvement of efficiency of quick sort the pivot can be ______________.
“the mean element”

28)What is the time complexity of linear search?Θ(n)

29)What is the time complexity of binary search?Θ(log2n)

30)What is the major requirement for binary search?


The given list should be sorted.

44
Analysis & Design of Algorithms Lab (BCSL404)

31). What are important problem types? (or) Enumerate some important types of problems.
1. Sorting 2. Searching
3. Numerical problems 4. Geometric problems
5. Combinatorial Problems 6. Graph Problems
7. String processing Problems

32). Name some basic Efficiency classes


1. Constant 2. Logarithmic 3. Linear 4. n log n
5. Quadratic 6. Cubic 7. Exponential 8. Factorial

33) What are algorithm design techniques?


Algorithm design techniques ( or strategies or paradigms) are general approaches to solving
problems algorithmatically, applicable to a variety of problems from different areas of
computing. General design techniques are:(i) Brute force (ii) divide and conquer
(iii) decrease and conquer (iv) transform and conquer
(v) greedy technique (vi) dynamic programming
(vii) backtracking (viii) branch and bound

34) How is an algorithm’s time efficiency measured?


Time efficiency indicates how fast the algorithm runs. An algorithm’s time efficiency is
measured as a function of its input size by counting the number of times its basic operation (running time) is executed. Basic operation is
the most time-consuming operation in the algorithm’s innermost loop.

35)Explain the greedy method.


Greedy method is the most important design technique, which makes a choice that looks best at that moment. A given ‘n’ inputs are
required us to obtain a subset that satisfies some constraints that is the feasible solution. A greedy method suggests that one can device
an algorithm that works in stages considering one input at a time.

36). Define feasible and optimal solution.


Given n inputs and we are required to form a subset such that it satisfies some given constraints then such a subset is called feasible
solution. A feasible solution either maximizes or minimizes the given objective function is called as optimal solution

37). What are the constraints of knapsack problem?


To maximize ∑pixi
The constraint is : ∑wixi ≥ m and 0 ≤ xi ≤ 1 1≤ i ≤ n
where m is the bag capacity, n is the number of objects and for each object i wi and pi are the weight and profit of object respectively.

38). Specify the algorithms used for constructing Minimum cost spanning tree.
a) Prim’s Algorithm
b) Kruskal’s Algorithm

39). State single source shortest path algorithm (Dijkstra’s algorithm).


For a given vertex called the source in a weighted connected graph, find shortest paths to all its
other vertices. Dijikstra’s algorithm applies to graph with non-negative weights only.

40). State efficiency of prim’s algorithm.


O(|v|2) (WEIGHT MATRIX AND PRIORITY QUEUE AS UNORDERED ARRAY)
O(|E| LOG|V|) (ADJACENCY LIST AND PRIORITY QUEUE AS MIN-HEAP)

45
Analysis & Design of Algorithms Lab (BCSL404)

41) State Kruskal Algorithm.


The algorithm looks at a MST for a weighted connected graph as an acyclic subgraph with |v|-1
edges for which the sum of edge weights is the smallest.

42) State efficiency of Dijkstra’s algorithm.


O(|v|2) (WEIGHT MATRIX AND PRIORITY QUEUE AS UNORDERED ARRAY)

46

You might also like