Ada Lab Manual
Ada Lab Manual
Design of Algorithms
Lab (BCSL404)
Labarotary Manual
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.
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.
● To design and implement various algorithms in C/C++ programming using suitable development
tools to address different computational challenges.
● 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).
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
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
SEMESTER – IV
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.
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
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 cost[10][10];
int parent[10];
int find(int i) {
while (parent[i] != 0)
i = parent[i];
return i;
if (i < j)
parent[i] = j;
else
parent[j] = i;
int main() {
scanf("%d", &n);
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
cost[i][j] = 999;
min = cost[i][j];
a = u = i;
b = v = j;
u = find(u);
v = find(v);
if (u != v) {
uni(u, v);
mincost += min;
} else {
return 0;
OUTPUT
Input Graph
Output Graph
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) {
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
Output Graph
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;
flyd(a, n);
return 0;
}
OUTPUT
Input Graph
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;
OUTPUT
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];
int main() {
int n, source, i, j;
dij(source, n);
return 0;
}
OUTPUT
Input Graph
#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]);
}
getch();
}
OUTPUT
INPUT GRAPH
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];
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);
OUTPUT
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);
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;
}
}
return 0;
OUTPUT
#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{");
for(i=0;i<count;i++)
printf("%d,",set[i]);
printf("}");
}
OUTPUT
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>
int main()
{
int n,i;
printf("Enter number of elements: ");
scanf("%d", &n); // Read the number of elements from the user
OUTPUT
plt.grid(True)
plt.show()
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>
int main()
{
int n;
printf("Enter number of elements: ");
scanf("%d", &n); // Read the number of elements from the user
return 0;
}
OUTPUT
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>
i = 0;
j = 0;
k = left;
free(L);
free(R);
}
int main()
{
int n,k;
printf("Enter the number of elements: ");
scanf("%d", &n);
// 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();
free(arr);
return 0;
}
OUTPUT
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);
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
}
}
}
OUTPUT
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.
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.
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.
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.
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.
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
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.
There are many different types of algorithms available, and they are listed below:
Randomized Algorithm
Hashing Algorithm
Recursive Algorithm
Searching Algorithm
Sorting Algorithm
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.
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.
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.
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?
Input: "Input" means that one or more quantities come from the outside.
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.
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.
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
Dynamic programming
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Data Access Arrangements (DAAs) connect a computer and modem to a public telephone network.
DAAs, called TLICs, are telephony line interface circuits (or Modules).
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.
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.)
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.
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.
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.
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.
many additional issues stemming from the initial issue. Recursively find solutions to each of the
individual subproblems.
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.
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.
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.
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.
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.