Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views52 pages

Ada Lab Manual

Uploaded by

dhanushree2628
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)
8 views52 pages

Ada Lab Manual

Uploaded by

dhanushree2628
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/ 52

Analysis &

Design of Algorithms
Lab (BCSL404)

Labarotary Manual

Dept. of Computer Science and Engineering (Data Science)

Adichunchanagiri Institute of Technology


(Affiliated to Visvesvaraya Technological University, Belagavi)
A.I.T Campus, Jyothinagar, Chikkamagaluru – 577102
www.aitckm.in
2023-24
Analysis & Design of Algorithms Lab (BCSL404`)

VISION

To build competent Engineers in the stream of Data Science to cope up with the challenges of
changing industry standards by facilitating learning activities to cater the societal and personal
needs.

MISSION

 To provide aspired technical education in the field of Data science by creating a learning
ambience aiding towards originality and innovation.
 To establish industry academia interaction to familiarize with needs of the industry and
providing exposure to the students in latest tools and technology.
 To inculcate moral ethics in students enabling them to become socially committed
professionals with leadership qualities.

Program Educational Objective (PEO)

 To achieve competence in fundamentals of Data Science concepts to address the ever


changing industry requirements.
 To enrich students to acquire skills needed by the industry and evolve with changing
technology landscapes.

Program Specific Outcome (PSO)

 The students are able to use advanced tools and technologies which will enable them to
adapt to real world projects with effective communication skills.
 The graduates will exhibit high standards of social and professional ethics in pursuing
higher education and research and persevere the essence of lifelong learning in the field of
Data Science Engineering.

Dept. of Data Science, AIT, CKM Page 1


Analysis & Design of Algorithms Lab (BCSL404`)

PROGRAM OUTCOMES (PO’s)

Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


1
and an engineering specialization to the solution of complex engineering problems.
Problem Analysis: Identify, formulate, review research literature, and analyze complex engineering
2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences and
engineering sciences.
Design/Development of Solutions: Design solutions for complex engineering problems and design
3 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.
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 for complex problems:
 That cannot be solved by straightforward application of knowledge, theories and techniques
applicable to the engineering discipline as against problems given at the end of chapters in a
typical text book that can be solved using simple engineering theories And techniques;
4  That may not have a unique solution .For example ,a design problem can be solved in many
Ways and lead to multiple possible solutions;
 That require consideration of appropriate constraints / requirements not explicitly given in the
problem statement such as cost, power requirement, durability, product life, etc.;
 Which need to be defined (modeled) within appropriate mathematical framework; and
 That often require use of modern computational concepts and tools, for example, in the design
of an antenna or a DSP filter.
Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
5 engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and Sustainability: Understand the impact of the professional engineering solutions in
7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
8
engineering practice.
Individual and Team Work: Function effectively as an individual, and as a member or leader in diverse
9
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
10 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.
Project Management and Finance: Demonstrate knowledge and understanding of the engineering and
11 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.
Life-long Learning: Recognize the need for, and have the preparation and ability to engage in
12
independent and lifelong learning in the broadest context of technological change.

Dept. of Data Science, AIT, CKM Page 2


Analysis & Design of Algorithms Lab (BCSL404`)

Course Learning Objectives

● To design and implement various algorithms in C/C++ programming using suitable development
tools to address different computational challenges.

● To apply diverse design strategies for effective problem-solving.

● To Measure and compare the performance of different algorithms to determine their efficiency
and suitability for specific tasks.

Laboratory Outcomes

1. Develop programs to solve computational problems using suitable algorithm design strategy.

2. Compare algorithm design strategies by developing equivalent programs and observing running
times for analysis (Empirical).

3. Make use of suitable integrated development tools to develop programs

4. Choose appropriate algorithm design techniques to develop solution to the computational and

complex problems.

5. Demonstrate and present the development of program, its execution and running time(s) and

record the results/inferences.

CO/PO P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 PSO1 PSO2

CO1 3 2 2 - - - - - 2 - - 1 1 1

CO2 3 2 1 - - - - - 2 - - 1 1 1

CO3 2 2 2 - - - - - 2 - - 1 1 1

CO4 2 2 2 - - - - - 2 - - 1 1 1

CO5 3 2 2 - - - - - 2 1 1 1
1

Dept. of Data Science, AIT, CKM Page 3


Analysis & Design of Algorithms Lab (BCSL404`)

Analysis & Design of Algorithms Lab

SEMESTER – IV

Course Code: BCSL404 CIE Marks: 50

Number of Contact Hours/Week 0:0:2 SEE Marks: 50

Credits – 1 Exam Hours: 02

Programs List

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

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

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

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

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

5. Design and implement C/C++ Program to obtain the Topological ordering of vertices in a
given digraph.

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

Dept. of Data Science, AIT, CKM Page 4


Analysis & Design of Algorithms Lab (BCSL404`)

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

8. 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.

9. 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.
Support the program with appropriate functions for each of the above operations

10. Design and implement C/C++ Program to 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 n. The
elements can be read from a file or can be generated using the random number generator.

11. Design and implement C/C++ Program to 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 n. The
elements can be read from a file or can be generated using the random number generator.

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

Dept. of Data Science, AIT, CKM Page 5


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>

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

int min, mincost = 0;

int cost[10][10];

int parent[10];

int find(int i) {

while (parent[i] != 0)

i = parent[i];

return i;

void uni(int i, int j) {

if (i < j)

parent[i] = j;

else

parent[j] = i;

int main() {

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

printf("Enter the no. of vertices\n");

Dept. of Data Science, AIT, CKM Page 6


Analysis & Design of Algorithms Lab (BCSL404`)

scanf("%d", &n);

printf("Enter the cost adjacency matrix\n");

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

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

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

if (cost[i][j] == 0)

cost[i][j] = 999;

printf("The edges of Minimum Cost Spanning Tree are\n\n");

while (ne < n) {

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

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

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

min = cost[i][j];

a = u = i;

b = v = j;

u = find(u);

v = find(v);

if (u != v) {

uni(u, v);

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

Dept. of Data Science, AIT, CKM Page 7


Analysis & Design of Algorithms Lab (BCSL404`)

mincost += min;

} else {

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

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

return 0;

OUTPUT

Input Graph

Output Graph

Dept. of Data Science, AIT, CKM Page 8


Analysis & Design of Algorithms Lab (BCSL404`)

Dept. of Data Science, AIT, CKM Page 9


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>
int ne = 1, min_cost = 0;
int cost[20][20];
int d[20];
int visited[20];
int v, u, a, b;

int main() {
int n, i, j, min, source;
printf("enter nos of vertices:");
scanf("%d", &n);
printf("Enter the cost adjacency matrix: ");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
}
}
for (i = 1; i <= n; i++) {
visited[i] = 0;
}
printf("Enter the root node:");
scanf("%d", &source);
visited[source] = 1;
printf("\nMinimum cost spanning tree is\n");
while (ne < n) {
min = 999;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (cost[i][j] < min) {
if (visited[i] == 0) {

Dept. of Data Science, AIT, CKM Page 10


Analysis & Design of Algorithms Lab (BCSL404`)

continue;
} else {
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}
}
if (visited[u] == 0 || visited[v] == 0) {
printf("\nEdge%d\t%d->%d=%d", ne++, a, b, min);
min_cost = min_cost + min;
visited[b] = 1;
}
cost[a][b] = cost[b][a] = 999;
}
printf("\nMinimum cost=%d", min_cost);
return 0;
}

OUTPUT

Input Graph

Dept. of Data Science, AIT, CKM Page 11


Analysis & Design of Algorithms Lab (BCSL404`)

Output Graph

Dept. of Data Science, AIT, CKM Page 12


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>
void flyd(int w[][10], int n) {
int i, j, k;
for (k = 1; k <= n; k++) {
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
w[i][j] = (w[i][j] < (w[i][k] + w[k][j])) ? w[i][j] : (w[i][k] + w[k][j]);
}
}
}
}

int main() {
int a[10][10];
int n, i, j;

printf("enter the number of vertices");


scanf("%d", &n);

printf("Enter the weighted matrix\n");


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

flyd(a, n);

printf("The shortest path matrix is\n");


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

return 0;
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 13


Analysis & Design of Algorithms Lab (BCSL404`)

Input Graph

Dept. of Data Science, AIT, CKM Page 14


Analysis & Design of Algorithms Lab (BCSL404`)

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

# include <stdio.h>
# include <conio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1) p[i][j]=1;
}
void main()
{
int i,j;

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


scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is showm below\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
}

Dept. of Data Science, AIT, CKM Page 15


Analysis & Design of Algorithms Lab (BCSL404`)

OUTPUT

Input Graph (Directed Graph)

Dept. of Data Science, AIT, CKM Page 16


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>
#define MAX 20
#define INF 999

int cost[MAX][MAX];
int d[MAX];
int visited[MAX];

void dij(int source, int n) {


int i, j, min, u, w;

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


visited[i] = 0;
d[i] = cost[source][i];
}
visited[source] = 1;
d[source] = 0;

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


min = INF;
for (i = 1; i <= n; i++) {
if (!visited[i] && d[i] < min) {
min = d[i];
u = i;
}
}
visited[u] = 1;
for (w = 1; w <= n; w++) {
if (cost[u][w] != INF && !visited[w]) {
if (d[w] > cost[u][w] + d[u]) {
d[w] = cost[u][w] + d[u];
}
}
}
}
}

int main() {
int n, source, i, j;

printf("Enter the number of vertices:\n");


scanf("%d", &n);

printf("Enter the cost adjacency matrix:\n");


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

Dept. of Data Science, AIT, CKM Page 17


Analysis & Design of Algorithms Lab (BCSL404`)

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


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

printf("\nEnter the source node:\n");


scanf("%d", &source);

dij(source, n);

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


if (i != source) {
printf("\nShortest path from %d to %d is %d\n", source, i, d[i]);
}
}

return 0;
}

OUTPUT

Input Graph

Dept. of Data Science, AIT, CKM Page 18


Analysis & Design of Algorithms Lab (BCSL404`)

Dept. of Data Science, AIT, CKM Page 19


Analysis & Design of Algorithms Lab (BCSL404`)

5. Design and implement C/C++ Program to obtain the Topological ordering of


vertices in a given digraph.

#include<stdio.h>
#include<conio.h>
int temp[10],k=0;
void sort(int a[][10],int id[],int n)
{
int i,j;
for(i=1; i<=n; i++)
{
if(id[i]==0)
{
id[i]=-1;
temp[++k]=i;
for(j=1; j<=n; j++)
{
if(a[i][j]==1 && id[j]!=-1)
id[j]--;
}
i=0;
}
}
}
void main()
{
int a[10][10],id[10],n,i,j;
printf("\nEnter the n value:");
scanf("%d",&n);
for(i=1; i<=n; i++)
id[i]=0;
printf("\nEnter the graph data:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==1)
id[j]++;
}
sort(a,id,n);
if(k!=n)
printf("\nTopological ordering not possible");
else
{
printf("\nTopological ordering is:");
for(i=1; i<=k; i++)
printf("%d ",temp[i]);
}

Dept. of Data Science, AIT, CKM Page 20


Analysis & Design of Algorithms Lab (BCSL404`)

getch();
}

OUTPUT

INPUT GRAPH

Dept. of Data Science, AIT, CKM Page 21


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>
int n, p;
int w[20];
int c[20];
int v[20][20];

int knapsack(int n, int p) {


int value;
if (v[n][p] < 0) {
if (p - w[n] < 0)
value = knapsack(n - 1, p);
else
value = (c[n] + knapsack(n - 1, p - w[n])) > knapsack(n - 1, p) ? (c[n] + knapsack(n - 1, p -
w[n])) : knapsack(n - 1, p);
v[n][p] = value;
}
return v[n][p];
}

void knaps() {
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= p; j++) {
if (i == 0 || j == 0)
v[i][j] = 0;
else
v[i][j] = -1;
}
}
}

int main() {
int d, i;
printf("Enter no. of items: ");
scanf("%d", &n);
printf("\nEnter the capacity:\n");
scanf("%d", &p);
printf("\nEnter the weights:\n");
for (i = 1; i <= n; i++)
scanf("%d", &w[i]);
printf("\nEnter the cost:\n");
for (i = 1; i <= n; i++)
scanf("%d", &c[i]);
knaps();
d = knapsack(n, p);

Dept. of Data Science, AIT, CKM Page 22


Analysis & Design of Algorithms Lab (BCSL404`)

printf("\nThe optimal solution is: %d\n", d);


return 0;
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 23


Analysis & Design of Algorithms Lab (BCSL404`)

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

#include <stdio.h>
int main() {
int i, j = 0, max_qty, m, n;
float sum = 0, max;
int array[2][20];

printf("Enter no of items\n");
scanf("%d", &n);

printf("Enter the weights of each items\n");


for (i = 0; i < n; i++)
scanf("%d", &array[0][i]);

printf("Enter the values of each knapsack :\n");


for (i = 0; i < n; i++)
scanf("%d", &array[1][i]);

printf("Enter maximum volume of max_knapsack\n");


scanf("%d", &max_qty);
m = max_qty;

while (m >= 0) {
max = 0;
for (i = 0; i < n; i++) {
if (((float)array[1][i] / (float)array[0][i]) > max) {
max = ((float)array[1][i] / (float)array[0][i]);
j = i;
}
}

if (array[0][j] > m) {
printf("Quantity of item number: %d added is %d\n", j + 1, m);
sum += m * max;
m = -1;
} else {
printf("Quantity of item number: %d added is %d\n", j + 1, array[0][j]);
m -= array[0][j];
sum += (float)array[1][j];
array[1][j] = 0;
}
}

printf("The total profit is %.2f\n", sum);

return 0;

Dept. of Data Science, AIT, CKM Page 24


Analysis & Design of Algorithms Lab (BCSL404`)

OUTPUT

Dept. of Data Science, AIT, CKM Page 25


Analysis & Design of Algorithms Lab (BCSL404`)

8. 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.

#include<stdio.h>
int s[10],d,n,set[10],count=0;
void display(int);
int flag = 0;
void main()
{
int subset(int,int);
int i;
printf("ENTER THE NUMBER OF THE ELEMENTS IN THE SET : ");
scanf("%d",&n);
printf("ENTER THE SET OF VALUES : ");
for(i=0;i<n;i++)
scanf("%d",&s[i]);
printf("ENTER THE SUM : ");
scanf("%d",&d);
printf("THE PROGRAM OUTPUT IS: ");
subset(0,0);
if(flag == 0)
printf("There is no solution");
}
int subset(int sum,int i)
{
if(sum == d)
{
flag = 1;
display(count);
return 0;
}
if(sum>d || i>=n)
return 0;
else
{
set[count]=s[i];
count++;
subset(sum+s[i],i+1);
count--;
subset(sum,i+1);
}
return 0 ;
}
void display(int count)
{
int i;
printf("\t{");

Dept. of Data Science, AIT, CKM Page 26


Analysis & Design of Algorithms Lab (BCSL404`)

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

OUTPUT

Dept. of Data Science, AIT, CKM Page 27


Analysis & Design of Algorithms Lab (BCSL404`)

9. 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.

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

// Function to perform selection sort on an array


void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i; // Assume the current element is the minimum
for (j = i+1; j < n; j++)
{
if (arr[j] < arr[min_idx])
{
min_idx = j; // Update min_idx if a smaller element is found
}
}
// Swap the found minimum element with the current element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

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

// Allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL)
{
printf("Memory allocation failed\n");
return 1; // Exit if memory allocation fails

Dept. of Data Science, AIT, CKM Page 28


Analysis & Design of Algorithms Lab (BCSL404`)

printf("Random Numbers generated are: \n");


for (i = 0; i < n; i++) {
arr[i] = rand() % 10000;
printf("%d\t", arr[i]);
}

// Measure the time taken to sort the array


clock_t start = clock();
selectionSort(arr, n);
clock_t end = clock();

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


for (int k = 0; k < n; k++)
printf("%d\t", arr[k]);

// Calculate and print the time taken to sort the array


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);

// Free the allocated memory


free(arr);
return 0;
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 29


Analysis & Design of Algorithms Lab (BCSL404`)

Commands to execute C program in ubuntu terminal


$:> gedit filename.c
$:> cc filename.c
$:> ./a.out

Commands to execute python program in ubuntu terminal (for graph generation)


$:> gedit filename.py
$:> python filename.py
(if python3 is installed then :> python3 filename.py)

If matplotlib is not installed then

$:> sudo apt update

$:> sudo apt-get install python3-matplotlib

Dept. of Data Science, AIT, CKM Page 30


Analysis & Design of Algorithms Lab (BCSL404`)

//Python code to plot the graph

import matplotlib.pyplot as plt

n_values = [100, 200, 300, 400, 500]

time_taken = [0.000017, 0.000063, 0.000179, 0.000225, 0.000335]

plt.plot(n_values, time_taken, marker='o')

plt.title('Selection Sort Time Complexity')

plt.xlabel('Number of Elements (n)')

plt.ylabel('Time taken (seconds)')

plt.grid(True)

plt.show()

Dept. of Data Science, AIT, CKM Page 31


Analysis & Design of Algorithms Lab (BCSL404`)

10. Design and implement C/C++ Program to 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 n. The elements can be read from a file or can be generated using the random
number generator.

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

// Function to swap two elements


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

// Partition function for Quick Sort


int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // Pivot element
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high - 1; j++)


{
if (arr[j] < pivot)
{
i++; // Increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Quick Sort function


void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);

Dept. of Data Science, AIT, CKM Page 32


Analysis & Design of Algorithms Lab (BCSL404`)

// Recursively sort elements before and after partition


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

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

// Allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL)
{
printf("Memory allocation failed\n");
return 1; // Exit if memory allocation fails
}

// Generate random numbers and store them in the array


printf("Random Numbers generated are: \n");
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100000;
printf("%d\n", arr[i]);
}

// Measure the time taken to sort the array


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

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


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

// Calculate and print the time taken to sort the array


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);

// Free the allocated memory


free(arr);

Dept. of Data Science, AIT, CKM Page 33


Analysis & Design of Algorithms Lab (BCSL404`)

return 0;
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 34


Analysis & Design of Algorithms Lab (BCSL404`)

Dept. of Data Science, AIT, CKM Page 35


Analysis & Design of Algorithms Lab (BCSL404`)

11. Design and implement C/C++ Program to 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 n. The elements can be read from a file or can be generated using the random
number generator.

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

// Function to merge two sorted arrays


void merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

int *L = (int *)malloc(n1 * sizeof(int));


int *R = (int *)malloc(n2 * sizeof(int));

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


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

i = 0;
j = 0;
k = left;

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

Dept. of Data Science, AIT, CKM Page 36


Analysis & Design of Algorithms Lab (BCSL404`)

while (i < n1)


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

while (j < n2)


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

free(L);
free(R);
}

// Function to implement Merge Sort


void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

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

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


if (arr == NULL)
{
printf("Memory allocation failed\n");
return 1; // Exit if memory allocation fails
}

Dept. of Data Science, AIT, CKM Page 37


Analysis & Design of Algorithms Lab (BCSL404`)

printf("Random Numbers generated are: \n");


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

// Repeat the sorting process multiple times to increase duration for timing
clock_t start = clock();
for (int i = 0; i < n; i++)
{
mergeSort(arr, 0, n - 1);
}
clock_t end = clock();

// Calculate the time taken for one iteration


printf("\n Elements after sorting \n");
for (int k = 0; k < n; k++)
printf("%d \n ", arr[k]);
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;

printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);

free(arr);
return 0;
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 38


Analysis & Design of Algorithms Lab (BCSL404`)

Dept. of Data Science, AIT, CKM Page 39


Analysis & Design of Algorithms Lab (BCSL404`)

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

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

int board[20],count;

int main()
{
int n,i,j;
void queen(int row,int n);

printf(" - N Queens Problem Using Backtracking -");


printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}

//function for printing the solution


void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)
printf("\t%d",i);

for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}

/*funtion to check conflicts


If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{

Dept. of Data Science, AIT, CKM Page 40


Analysis & Design of Algorithms Lab (BCSL404`)

//checking column and digonal conflicts


if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}

return 1; //no conflicts


}

//function to check for proper positioning of queen


void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}

OUTPUT

Dept. of Data Science, AIT, CKM Page 41


Analysis & Design of Algorithms Lab (BCSL404`)

Dept. of Data Science, AIT, CKM Page 42


Analysis & Design of Algorithms Lab (BCSL404`)

VIVA QUESTIONS

1. What is an Algorithm?

The Term 'Algorithm' refers to the set of instructions that must be followed to solve a problem.
The logical description of the instructions can be executed to carry out a critical function.
Algorithms are typically generated independently of primary languages, implying that an
algorithm can be accomplished in more than one programming language.

2. What is the DAA algorithm?

A DAA algorithm is a procedure that accomplishes its goal effectively and can be expressed in a
finite amount of time and space. DAA algorithms are instructions for computers to follow when
they need to perform a calculation, process some data, or use some form of automated reasoning
to resolve a problem.

3. What is DAA design?

The fields of algorithm design and analysis help design algorithms that can be used to solve various
problems in computer science. It is beneficial to design and analyzes the logic governing how the
program will function before developing its actual code.

4. What is the Algorithm's Time Complexity?

The time complexity of an algorithm was the total amount of time required for the program to run
until it was finished. In most cases, it is expressed with the notation known as the big O. The length
of time needed for a program to run entirely was indicated by the Algorithm's time complexity.

5. What is Data Structures?

Data Structures are one of the most basic ways to store and display data. Data is how a processor
shows facts, ideas, and instructions for all computing tasks. Data structures are the different ways
all this information can be organized helpfully.

Dept. of Data Science, AIT, CKM Page 43


Analysis & Design of Algorithms Lab (BCSL404`)

6. What is Backtracking in DAA?

The term "Backtracking" refers to a recursive algorithmic technique for solving problems by first
attempting to build a solution and then discarding any solutions that don't meet the problem's
constraints at that stage. You could say that going backward is better than going forwards with
force. The backtracking method involves searching through all options to find a solution to a
problem

7. What is a Greedy method in DAA?

Greedy algorithms construct a solution piece by piece, selecting the subsequent component in a
way that provides an immediate benefit. This method never takes prior decisions into account.
This method is primarily employed to address optimization issues.

8. What are the different types of algorithms?

There are many different types of algorithms available, and they are listed below:

Randomized Algorithm

Hashing Algorithm

Recursive Algorithm

Brute Force Algorithm

Searching Algorithm

Sorting Algorithm

9. What is Asymptotic Notation?

A method that can represent the behavior of functions when they are either in the limit or when
they are not bound. The notations are explained in terms of methods, and the domains of those
methods are the set of natural numbers represented by the numbers 0 through 2.

Dept. of Data Science, AIT, CKM Page 44


Analysis & Design of Algorithms Lab (BCSL404`)

Notations of this kind make defining the worst-case running time function T more convenient (n).
It is possible to extend it to cover the realm of real numbers.

10. What is a Dynamic Method in DAA?

Similarly to the divide-and-conquer strategy, the key to success in dynamic programming is to


merge the results of previously solved subproblems. In addition, the dynamic programming
algorithm only needs to compute the solution to each sub-problem once, and then it can reuse that
information from a table.

11. What is Dijkstra's Algorithm?

Dijkstra's Algorithm computes the shortest path from a given source vertex to a given target vertex
in a weighted graph or digraph by solving the single-source shortest path problem. Dijkstra's
Algorithm works properly for graphs with positive weights.

12. What exactly are Huffman Trees?

A Huffman tree is a binary tree that shortens the time it takes to travel from the root node to each
of the leaves by using weights that have already been determined. The most effective application
of Huffman trees is to create a Huffman code with their help.

13. What criteria are used to make the Algorithm work better?

The various standards used to raise the Algorithm's effectiveness include

Input: "Input" means that one or more quantities come from the outside.

Output: The composition of at least one quantity constitutes an output.

Clarity: Every guideline is easy to understand and follows.

Finiteness: Algorithms are said to be "finite" if they can be solved in a finite number of steps by
following their instructions to the letter.

Effectiveness: Efficient teaching requires starting at the very beginning.

Dept. of Data Science, AIT, CKM Page 45


Analysis & Design of Algorithms Lab (BCSL404`)

14. What is the Knapsack Problem?

Assume we have n elements, where we know their weights wi and values vi for i=1, 2, etc. Given
n and W, identify the most valuable subsets of the elements that fit in a knapsack of size W.

When sorting the components of a specific instance, it helps to do so in descending value-to-weight


order. It means that the payoff per unit of weight is highest for the first element and lowest for the
last.

15. What is Dynamic Huffman Encoding?

The dynamic Huffman encoding tree is updated after each character is read. It guarantees the
highest degree of precision in the coding process. For the most precise coding, this is a must. To
avoid the problems inherent in the bare-bones implementation, we turned to dynamic Huffman n-
coding.

16. Write the difference between dynamic programming and the greedy method?

Greedy method

There is always only one path that can unfold.

It need not always supply the best possible answer.

Dynamic programming

There are a plethora of options from which to choose.

Provides the best possible answer every time

17. What are Minimum Spanning Trees?

A tree is a spanning tree for a linked graph if its set of vertices is the same as the graph's set of
vertices and its edges are a subgroup of the graph's edge set.

A spanning tree is a component of every linked graph. The sum of the weights of each edge in a
spanning tree is the tree's weight, denoted by the symbol w (T). The Minimum Spanning Tree,
abbreviated MST, is a spanning tree with the least amount of weight that is practically possible.

Dept. of Data Science, AIT, CKM Page 46


Analysis & Design of Algorithms Lab (BCSL404`)

18. What exactly do you mean by the Huffman code?

A Huffman code is an optimal variable-length prefix tree encoding method. This method works
by assigning bit strings to characters in a text based on the number of times those characters appear.

19. What exactly is Backtracking?

The generation of depth-first nodes is referred to as backtracking when using the bounding method.
The backtracking method can find the solution in a significantly smaller number of iterations than
m trials.

20. What is a Sorting Network?

A sorting network is a mathematical representation of the wired network and comparator modules
used to order a set of numbers.

This model is used to sort the numbers. Every comparator has two wires that connect and sort the
values by sending the value lower to one wire and the other wire higher. In contrast, with
comparison sorting algorithms, the series of comparisons is determined by the outcome of the
comparisons that came before it. Because of this independence of comparison series, parallel
execution of the methods can benefit greatly from having this property.

21. What is time Complexity in DAA?

Time complexity, a particular case of computational complexity, describes the time it takes to run
an algorithm. The time complexity algorithm is the specific time that must elapse before any
statement can be executed. Accordingly, this is highly dependent on the amount of data being
processed.

22. What is the principle of optimality in DAA?

When the subsolutions of a problem's optimal solution are also the optimal solutions for their
respective subproblems, we say that the problem satisfies the principle of optimality. It means that
the optimal solution to the problem has subsolutions that satisfy the principle.

Examples: The principle of optimality can be shown to be satisfied by the shortest path problem.

23. What is reliability design in DAA?

The probability that a product will continue to function past the time specified and under the
specified conditions is known as reliability. It implies that even if a keyboard has 99% reliability
over 1000 hours, 1% of those 1000 hours could still see a malfunction.

Dept. of Data Science, AIT, CKM Page 47


Analysis & Design of Algorithms Lab (BCSL404`)

24. What is the order of growth in DAA?

The order of growth of an algorithm provides a rough estimate of the amount of time needed to
execute a computer program as the size of the input variable increases. The order of growth does
not take into account the constant factor that is required for fixed operations. Instead, it emphasizes
the operations that expand in proportion to the input size.

25. What is the Importance of Algorithms?

An algorithm is merely a procedure for accomplishing a goal. Computers, smartphones, and


websites can't perform their tasks or make decisions without them; they're the foundation of
programming. Many of the activities we engage in daily are, like algorithms, used by technology.

26. Explain the Bubble sort algorithms.

Bubble sorting involves splitting the list into two parts. They are sorted and unsorted. The smallest
item in a sublist that hasn't been sorted is "bubbled." When the smallest piece of the wall is shifted,
the entire wall shifts forward one space. The idea behind bubble sort was to highlight the item at
the top of the list in a giant bubble. It does not matter if the highest or lowest item is bubbled. In
this variant, two adjacent components are switched around based on a comparison. Since bubble
sort performs a full array check, sorting a record with n elements can take up to n-1 iterations.

27. Explain the Quick sort algorithms.

The Quicksort algorithm relies on division to sort the data. The term "partition exchange sorting"
is also used to refer to this technique in some contexts. The quick sort algorithm involves picking
one item from an array and then rearranging the rest of the data so that it revolves around that item.
This item caused the initial list to be divided in half. The "pivot" is the currently chosen option.
Any items whose values are less than the pivot are shifted to the left, and those whose values are
more significant than the pivot are shifted to the right when the pivot is selected. Until sub-lists
containing only one item are found, selecting a pivot and dividing the list is repeated in a while
loop.

28. What is DAA Programming?

Data Access Arrangements (DAAs) connect a computer and modem to a public telephone network.
DAAs, called TLICs, are telephony line interface circuits (or Modules).

29. What exactly is NP-Complete?

Any other NP problem can be simplified to an NP-Complete problem in a polynomial amount of


time, which means that an NP-Complete problem is just as tricky as any other problem in this
category.

Dept. of Data Science, AIT, CKM Page 48


Analysis & Design of Algorithms Lab (BCSL404`)

30. What is the Knapsack Problem in DAA?

The DAA knapsack problem is challenging in combinatorial optimization. Given a set of items
with weights and values, find the optimal number of each item to include in the collection such
that the sum of the weights is as tiny as possible and the sum of the values is as large as possible.

31. What is a multistage graph in DAA?

The nodes in a multistage graph are directed and weighted, and the edges between them can only
go from one stage to the next (This means that there is no edge connecting the vertices of the same
stage, nor is there an edge connecting a vertex of the current stage to a vertex of the stage before
it.)

32. What exactly is Binary Search?

Binary search is superior to linear search. On a non-sorted data structure, however, it cannot be
tested. The basis of binary search is the divide-and-conquer tactic. The binary search starts by
testing the central element of the array's data. Doing this can determine whether a specific event
or piece of information occurs in the first or second half. We do not need to check the second half
if the object is found in the first half and vice versa if it is discovered in the second half.

33. Explain the Insertion Sort algorithms.

In both selection and bubble sorts, items are interchanged. In contrast, insertion sort does not
exchange items. Like card insertion, the item is inserted into the insertion sort at the appropriate
location.

34. What exactly do you mean by "optimal solution"?

We first identify the subset of the input that can satisfy the constraints to solve the input problem.
A workable solution is any subset that complies with these conditions. The solution that maximizes
or minimizes the pertinent variables is always the best solution to a problem.

35. Why do we study algorithms in DAA?

People who aren't familiar with the inner workings of algorithms or how to strategically use them
have a clear disadvantage over tech professionals who have taken the time to study them.
Participating in a web development Bootcamp designed to accelerate the development of web-
based skills is one method by which you can broaden your understanding of the characteristics of
algorithms.

36. Which Algorithm is used in DAA?

It takes a top-down approach and uses the divide-and-conquer strategy.The divide-and-conquer


strategy is accompanied by algorithms that consist of three steps, which are as follows: Create

Dept. of Data Science, AIT, CKM Page 49


Analysis & Design of Algorithms Lab (BCSL404`)

many additional issues stemming from the initial issue. Recursively find solutions to each of the
individual subproblems.

37. What is the function of DAA instruction?

DAA is an abbreviation for decimal adjust accumulator and is used in BCD addition. The DAA
instruction converts the accumulator's binary values to BCD.

38. How does the asymmetric encryption algorithm work?

To encrypt something means transforming it from its "plaintext" form into an unbreakable
"Ciphertext" form. The content is "keyed" to an algorithmic string of bits that serves as a basis for
estimation in the conversion process. The more significant the key, the more possible combinations
for creating the ciphertext. Most algorithms for secure communication employ fixed-length blocks
of input—typically 64 bits to 128 bits in length—while others employ the stream technique.

39. What exactly is Dynamic Programming?

DP is an alternative strategy for optimal substructure problems. The optimal solution to a problem
will include the answers to any subproblems that must be solved. Not all optimal solutions to
individual subproblems will necessarily contribute to a complete answer. Each top-down
subproblem can be tackled in any order, making the divide-and-conquer strategy very flexible.

40. What are some examples of Data Structures Applications?

This is a common data structure question asked during interviews. Expertise in various fields,
including but not limited to statistical analysis, operating systems, numerical analysis, compiler
design, artificial intelligence, graphics, database management, and simulation.

41. What exactly is the distinction between file structure and storage structure?

The access to the memory area is what sets these two types apart. The data structure stored in the
computer system's memory is called the storage structure. On the other hand, the file structure is
the storage structure that is stored in the auxiliary memory.

Dept. of Data Science, AIT, CKM Page 50


Analysis & Design of Algorithms Lab (BCSL404`)

42. Which sorting Algorithm is best?

Quicksort is the most efficient sorting Algorithm, which explains why it is widely used. The first
step is to choose a pivot number. This number will divide the data, with smaller numbers to its left
and more significant numbers to its right.

Dept. of Data Science, AIT, CKM Page 51

You might also like