0% found this document useful (0 votes)
21 views57 pages

ADA Manual To Students

The document outlines the syllabus for the Analysis & Design of Algorithms Lab (BCSL404), detailing various programming tasks to be implemented in C/C++ using algorithms like Kruskal's, Prim's, Dijkstra's, and others. It includes program outcomes, educational objectives, and mappings of experiments to course outcomes. Additionally, it emphasizes the importance of ethical considerations, teamwork, and communication skills in engineering education.
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 views57 pages

ADA Manual To Students

The document outlines the syllabus for the Analysis & Design of Algorithms Lab (BCSL404), detailing various programming tasks to be implemented in C/C++ using algorithms like Kruskal's, Prim's, Dijkstra's, and others. It includes program outcomes, educational objectives, and mappings of experiments to course outcomes. Additionally, it emphasizes the importance of ethical considerations, teamwork, and communication skills in engineering education.
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/ 57

Analysis & Design of Algorithms Lab BCSL404

Index
Sl. No. Content Page
No.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of
1 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.
3 b. Design and implement C/C++ Program to find the transitive closure using
Warshal's algorithm
Design and implement C/C++ Program to find shortest paths from a given

4 vertex in a weighted connected graph to other vertices using Dijkstra's


algorithm.

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

5 vertices in a given digraph

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

Design and implement C/C++ Program to solve discrete Knapsack and


7 continuous Knapsack problems using greedy approximation method

Design and implement C/C++ Program to find a subset of a given set S = {sl ,
8 s2,.....,sn} of n positive integers whose sum is equal to a given positive integer
d.
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
9 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.

Dept. of CSE, KLS VDIT Haliyal. Page 1


Analysis & Design of Algorithms Lab BCSL404
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
10 time taken versus n. The elements can be read from a file or can be generated
using the random number generator

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

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


12 Backtracking

Virtual Lab Programs

1 Depth First Search

2 Breadth First Search

Dept. of CSE, KLS VDIT Haliyal. Page 2


Analysis & Design of Algorithms Lab BCSL404

PROGRAM OUTCOMES(POs)
Program Outcomes as defined by NBA (PO) Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate
effectively on complex engineering
activities with the engineering community
and with society at large, such as, being
able to comprehend and write effective
reports and design documentation, make
effective presentations, and give and
receive clear instructions.
11. Project management and finance:
Demonstrate knowledge and
understanding of the engineering and
management principles and apply these to
one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

Dept. of CSE, KLS VDIT Haliyal. Page 3


Analysis & Design of Algorithms Lab BCSL404
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Vision (College)
To nurture talent and enrich society through excellence in technical education, research and
innovation.
Mission (College)
1. To augment innovative Pedagogy, kindle quest for interdisciplinary learning & to enhance
conceptual understanding.
2. To build competence, professional ethics & develop entrepreneurial thinking.
3. To strengthen Industry Institute Partnership & explore global collaborations.
4. To inculcate culture of socially responsible citizenship.
5. To focus on Holistic & Sustainable development.
Vision (Dept)

To achieve excellence in technical education, research, and innovation in computer science


and Engineering by emphasizing on global trending technologies.

Mission (Dept)
To train students with conceptual understanding through innovative pedagogies.
To imbibe professional, research, and entrepreneurial skills with a commitment to the
nation’s development at large.
To strengthen the industry-institute Interaction.
To promote life–long learning with a sense of societal & ethical responsibilities.

Program Educational Objectives ( PEO )

Dept. of CSE, KLS VDIT Haliyal. Page 4


Analysis & Design of Algorithms Lab BCSL404
To develop an ability to identify and analyze the requirements of Computer
PEO1
Science and Engineering in design and providing novel engineering solutions.
To develop abilities to work in team on multidisciplinary projects with effective
PEO2
communication skills, ethical qualities and leadership roles.
To develop abilities for successful Computer Science Engineer and achieve higher
PEO3
career goals.
Program Specific Outcomes ( PSO )
To develop the ability to model real-world problems using appropriate data
PSO 1
structure and suitable algorithms in the area of Data Processing, System
Engineering, and Networking for varying complexity.
To develop an ability to use modern computer languages, environments and
PSO 2
platforms in creating innovative career.

Dept. of CSE, KLS VDIT Haliyal. Page 5


Analysis & Design of Algorithms Lab BCSL404
CO’s And PO’s Mapping Chart

Subject with code: Analysis and Design of Algorithms Laboratory AY: 2024-25
th
Semester: 4
S.No. Description PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Develop programs to
solve computational
1 problems using suitable 3 1 1
algorithm design
strategy.
Compare algorithm
design strategies by
developing equivalent
2 programs and 3 2 1 1 1 1
observing running
times for analysis
(Empirical).
Make use of suitable
integrated development
3 3 2 1 1 1 1
tools to develop
programs
Choose appropriate
algorithm design
techniques to develop
4 3 2 1 1 1 1
solution to the
computational and
complex problems
Demonstrate and present
the development of
program, its execution
5 3 1 1 1 1 1
and running time(s) and
record the
results/inferences
Degree of compliance Low: 1 Medium: 2 High: 3

Evaluation: CIA

Particulars Marks Total


Performance 20
35
Journal 15
Addon Course 05
15
Lab IA 10
Grand Total 50

Dept. of CSE, KLS VDIT Haliyal. Page 6


Analysis & Design of Algorithms Lab BCSL404

Mapping of Experiments with CO, PO and PSO


Sl.
Experiment Details CO PO PSO
No.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
1 CO1 1 1
given connected undirected graph using Kruskal's algorithm.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
2 CO1 1 1
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.
3 CO1 1 1
b. Design and implement C/C++ Program to find the transitive closure using
Warshal's algorithm
Design and implement C/C++ Program to find shortest paths from a given vertex in a
4 CO1 1 1
weighted connected graph to other vertices using Dijkstra's algorithm.
5 Design and implement C/C++ Program to obtain the Topological ordering of
5 CO2 2 1
vertices in a given digraph
Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
6 CO2 2 1
Programming method
7 Design and implement C/C++ Program to solve discrete Knapsack and continuous
7 CO2 2 1
Knapsack problems using greedy approximation method
Design and implement C/C++ Program to find a subset of a given set S = {sl ,
8 CO2 2 1
s2,.....,sn} of n positive integers whose sum is equal to a given positive integer d.
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
CO3,
values of n> 5000 and record the time taken to sort. Plot a graph of the time taken
9 CO5 3 1
versus n. The elements can be read from a file or can be generated using the
random number generator.
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
CO3,
10 values of n> 5000 and record the time taken to sort. Plot a graph of the time taken 3 1
CO5
versus n. The elements can be read from a file or can be generated using the
random number generator
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
CO3,
11 values of n> 5000, and record the time taken to sort. Plot a graph of the time taken 3 1
CO5
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 CO4 3 1

Dept. of CSE, KLS VDIT Haliyal. Page 7


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.

DESCRIPTION:
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connectedweighted
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 (a minimum spanning tree for each connected component). Kruskal'salgorithm is an example of a greedy
algorithm

ALGORITHM:
Let G = (V, E) be the given graph, with | V| = n
{
Start with a graph T = (V,$ \phi$) consisting of only the
vertices of G and no edges; /* This can be viewed as n connected components, each vertex being one
connected component */
Arrange E in the order of increasing costs;
for (i = 1, i$ \leq$n - 1, i + +)
{
Select the next smallest cost edge;
if (the edge connects two different connected components)
add the edge to T;
}
}

Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
clrscr();
printf("\n\tImplementation of Kruskal's algorithm\n");

Dept. of CSE, KLS VDIT Haliyal. Page 8


Analysis & Design of Algorithms Lab BCSL404
printf("\nEnter the no. of vertices:");
scanf("%d",&n);
printf("\nEnter 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");
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(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
getch();

Dept. of CSE, KLS VDIT Haliyal. Page 9


Analysis & Design of Algorithms Lab BCSL404
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

Output:

Dept. of CSE, KLS VDIT Haliyal. Page 10


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.

Description:
The program uses prim's algorithm which is based on minimum spanning tree for a connected undirected
graph.A predefinined cost adjecency matrix is the input.To find the minimum spanning tree, we choose the
source node at random and in every step we find the node which is closest as well as having the least cost from
the previously selected node.And also the cost of selected edge is being added to variable sum.Based on the
value of sum, the presence of the minimum spanning tree is found.

Algorithm:
Input: A non-empty connected weighted graph with vertices V and edges E (the weights can be negative).
Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V, Enew = {}
Repeat until Vnew = V:
Choose an edge {u, v} with minimal weight such that u is in Vnew and v is not (if there are multiple edges
with the same weight, any of them may be picked)
Add v to Vnew, and {u, v} to Enew
Output: Vnew and Enew describe a minimal spanning tree

Program
#include<stdio.h>
#include<conio.h>
int n,cost[10][10],temp,nears[10];
void readv();
void primsalg();
void readv()
{
int i,j;
printf("\n Enter the No of nodes or vertices:");
scanf("%d",&n);
printf("\n Enter the Cost Adjacency matrix of the given graph:");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if((cost[i][j]==0) && (i!=j))
{

Dept. of CSE, KLS VDIT Haliyal. Page 11


Analysis & Design of Algorithms Lab BCSL404
cost[i][j]=999;
}
}
}
}
void primsalg()
{
int k,l,min,a,t[10][10],u,i,j,mincost=0;
min=999;
for(i=1;i<=n;i++) //To Find the Minimum Edge E(k,l)
{
for(u=1;u<=n;u++)
{
if(i!=u)
{
if(cost[i][u]<min)
{
min=cost[i][u];
k=i;
l=u;
}
}
}
}
t[1][1]=k;
t[1][2]=l;
printf("\n The Minimum Cost Spanning tree is...");
printf("\n(%d,%d)-->%d",k,l,min);
for(i=1;i<=n;i++)
{
if(i!=k)
{
if(cost[i][l]<cost[i][k])
{
nears[i]=l;
}
else
{

Dept. of CSE, KLS VDIT Haliyal. Page 12


Analysis & Design of Algorithms Lab BCSL404
nears[i]=k;
}
}
}
nears[k]=nears[l]=0;
mincost=min;
for(i=2;i<=n-1;i++)
{
j = findnextindex(cost,nears);
t[i][1]=j;
t[i][2]=nears[j];
printf("\n(%d,%d)-->%d",t[i][1],t[i][2],cost[j][nears[j]]);
mincost=mincost+cost[j][nears[j]];
nears[j]=0;
for(k=1;k<=n;k++)
{
if(nears[k]!=0 && cost[k][nears[k]]>cost[k][j])
{
nears[k]=j;
}
}
}
printf("\n The Required Mincost of the Spanning Tree is:%d",mincost);
}
int findnextindex(int cost[10][10],int nears[10])
{
int min=999,a,k,p;
for(a=1;a<=n;a++)
{
p=nears[a];
if(p!=0)
{
if(cost[a][p]<min)
{
min=cost[a][p];
k=a;
}
}

Dept. of CSE, KLS VDIT Haliyal. Page 13


Analysis & Design of Algorithms Lab BCSL404
}
return k;
}
void main()
{
clrscr();
readv();
primsalg();
getch();
}

Output:

Dept. of CSE, KLS VDIT Haliyal. Page 14


Analysis & Design of Algorithms Lab BCSL404
3a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's algorithm

DESCRIPTION
The Floyd's algorithm is a graph analysis algorithm for finding shortest paths in a weighted graph with positive
or negative edge weights (but with no negative cycles, see below) and also for finding transitive closure of a
relation R. A single execution of the algorithm will find the lengths (summed weights) of the shortest paths
between all pairs of vertices, though it does not return details of the paths themselves.
ALGORITHM:
let dist be a |V| x |V| array of minimum distances initialized to infinity
for each vertex v
dist[v][v] <- 0
for each edge (u,v)
dist[u][v] <- w(u,v) // the weight of the edge (u,v)
for k from 1 to |V|
for i from 1 to |V|
for j from 1 to |V|
if dist[i][j] > dist[i][k] + dist[k][j]
dist[i][j] <- dist[i][k] + dist[k][j]
end if

Program
#include<stdio.h>
#include<conio.h>
void readf();
void amin();
int cost[20][20],a[20][20];
int i,j,k,n;
void readf()
{
printf("\n Enter the no of vertices:");
scanf("%d",&n);
printf("\n Enter the Cost of vertices:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0 && (i!=j))

Dept. of CSE, KLS VDIT Haliyal. Page 15


Analysis & Design of Algorithms Lab BCSL404
cost[i][j]=999;
a[i][j]=cost[i][j];
}
}
}
void amin()
{
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
printf("\n The All pair shortest path is:");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
}
}
void main()
{
clrscr();
readf();
amin();
getch();
}

Dept. of CSE, KLS VDIT Haliyal. Page 16


Analysis & Design of Algorithms Lab BCSL404

Output:

Dept. of CSE, KLS VDIT Haliyal. Page 17


Analysis & Design of Algorithms Lab BCSL404
3b. Design and implement C/C++ Program to find the transitive closure using Warshal's algorithm.

DESCRIPTION :
Warshall's algorithm determines whether there is a path between any two nodes in the graph. It does not give
the number of the paths between two nodes. According to Warshall's algorith,a path exists between two
vertices i, j, iff there is a path from i to j or there is a path from i to j through 1,..,k intermadiate nodes.

ALGORITHM:
n = |V|
t(0) = the adjacency matrix for G

for i in 1..n do
t(0)[i,i] = True
end for

for k in 1..n do
for i in 1..n do
for j in 1..n do
t(k)[i,j] = t(k-1)[i,j] OR
(t(k-1)[i,k] AND t(k-1)[k,j])
end for
end for
end for
return t(n)

Program
#include<stdio.h>
const int MAX = 100;
void WarshallTransitiveClosure(int graph[MAX][MAX], int numVert);
int main(void)
{
int i, j, numVert;
int graph[MAX][MAX];
printf("Warshall's Transitive Closure\n");
printf("Enter the number of vertices : ");
scanf("%d",&numVert);

Dept. of CSE, KLS VDIT Haliyal. Page 18


Analysis & Design of Algorithms Lab BCSL404
printf("Enter the adjacency matrix :-\n");
for (i=0; i<numVert; i++)
for (j=0; j<numVert; j++)
scanf("%d",&graph[i][j]);
WarshallTransitiveClosure(graph, numVert);
printf("\nThe transitive closure for the given graph is :-\n");
for (i=0; i<numVert; i++)
{
for (j=0; j<numVert; j++)
{
printf("%d\t",graph[i][j]);
}
printf("\n");
}
return 0;
}

void WarshallTransitiveClosure(int graph[MAX][MAX], int numVert)


{
int i,j,k;
for (k=0; k<numVert; k++)
{
for (i=0; i<numVert; i++)
{
for (j=0; j<numVert; j++)
{
if (graph[i][j] || (graph[i][k] && graph[k][j]))
graph[i][j] = 1;
}
}
}
}

Dept. of CSE, KLS VDIT Haliyal. Page 19


Analysis & Design of Algorithms Lab BCSL404
OUTPUT
Enter the number of vertices : 4 Enter the adjacency matrix :- 0 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0
The transitive closure for the given graph is :- 1 0 1 0
0101
1010
0101
Warshall's Transitive Closure Enter the number of vertices : 4 Enter the adjacency matrix :-
0110100110010110
The transitive closure for the given graph is :- 1 1 1 1
1111
1111
1111

Dept. of CSE, KLS VDIT Haliyal. Page 20


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.

DESCRIPTION:
To find the shortest path between points, the weight or length of a path is calculated as the sum of the weights
of the edges in the path.
A path is a shortest path is there is no path from x to y with lower weight.
Dijkstra's algorithm finds the shortest path from x to y in order of increasing distance from x. That is, it chooses
the first minimum edge, stores this value and adds the next minimum value from the next edge it selects.
It starts out at one vertex and branches out by selecting certain edges that lead to new vertices.
It is similar to the minimum spanning tree algorithm, in that it is "greedy", always choosing the closest edge in
hopes of an optimal solution.
ALGORITHM:
function Dijkstra(Graph, source):
for each vertex v in Graph: // Initializations
dist[v] := infinity ; // Unknown distance function from
// source to v
previous[v] := undefined ; // Previous node in optimal path
end for // from source
dist[source] := 0 ; // Distance from source to source
Q := the set of all nodes in Graph ; // All nodes in the graph are
// unoptimized - thus are in Q
while Q is not empty: // The main loop
u := vertex in Q with smallest distance in dist[] ; // Source node in first case
remove u from Q ;
if dist[u] = infinity:
break ; // all remaining vertices are
end if // inaccessible from source

for each neighbor v of u: // where v has not yet been


// removed from Q.
alt := dist[u] + dist_between(u, v) ;
if alt < dist[v]: // Relax (u,v,a)
dist[v] := alt ;
previous[v] := u ;
decrease-key v in Q; // Reorder v in the Queue
end if
end for

Dept. of CSE, KLS VDIT Haliyal. Page 21


Analysis & Design of Algorithms Lab BCSL404
end while
return dist;
end function

Program
#include<ostream>
#include<cstdio>
using namespace std;

const int MAXNODES = 10,INF = 9999;

void fnDijkstra(int [][MAXNODES], int [], int [], int[], int, int, int);

int main(void)
{
int n,cost[MAXNODES][MAXNODES],dist[MAXNODES],visited[MAXNODES],path[MAXNODES],i,j,source,dest;

cout << "\nEnter the number of nodes\n";


cin >> n;
cout << "Enter the Cost Matrix\n" << endl;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
cin >> cost[i][j];

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


{
getchar();
cout << "\n//For Source Vertex : " << source << " shortest path to other vertices//"<< endl;
for (dest=0; dest < n; dest++)
{
fnDijkstra(cost,dist,path,visited,source,dest,n);

if (dist[dest] == INF)
cout << dest << " not reachable" << endl;
else
{
cout << endl;
i = dest;
do
{
cout << i << "<--";

Dept. of CSE, KLS VDIT Haliyal. Page 22


Analysis & Design of Algorithms Lab BCSL404
i = path[i];
}while (i!= source);
cout << i << " = " << dist[dest] << endl;
}
}
cout << "Press Enter to continue...";
}

return 0;
}

void fnDijkstra(int c[MAXNODES][MAXNODES], int d[MAXNODES], int p[MAXNODES], int s[MAXNODES], int so,
int de, int n)
{
int i,j,a,b,min;

for (i=0;i<n;i++)
{
s[i] = 0;
d[i] = c[so][i];
p[i] = so;
}

s[so] = 1;

for (i=1;i<n;i++)
{
min = INF;
a = -1;
for (j=0;j<n;j++)
{
if (s[j] == 0)
{
if (d[j] < min)
{
min = d[j];
a = j;
}
}
}

if (a == -1) return;

s[a] = 1;
Dept. of CSE, KLS VDIT Haliyal. Page 23
Analysis & Design of Algorithms Lab BCSL404

if (a == de) return;

for (b=0;b<n;b++)
{
if (s[b] == 0)
{
if (d[a] + c[a][b] <d[b])
{
d[b] = d[a] + c[a][b];
p[b] = a;
}
}
}
}
}
Output
Enter the number of nodes 5 Enter the Cost Matrix
0 3 9999 7 9999 3 0 4 2 9999 9999 4 0 5 6 7 2 5 0 4 9999 9999 6 4 0
//For Source Vertex : 0 shortest path to other vertices//
0<--0 = 0
1<--0 = 3
2<--1<--0 = 7
3<--1<--0 = 5
4<--3<--1<--0 = 9 Press Enter to continue...
//For Source Vertex : 1 shortest path to other vertices//
0<--1 = 3
1<--1 = 0
2<--1 = 4
3<--1 = 2
4<--3<--1 = 6 Press Enter to continue...
//For Source Vertex : 2 shortest path to other vertices//
0<--1<--2 = 7
1<--2 = 4
2<--2 = 0
3<--2 = 5
4<--2 = 6 Press Enter to continue...
//For Source Vertex : 3 shortest path to other vertices//
0<--1<--3 = 5
1<--3 = 2
2<--3 = 5
3<--3 = 0
4<--3 = 4 Press Enter to continue...

Dept. of CSE, KLS VDIT Haliyal. Page 24


Analysis & Design of Algorithms Lab BCSL404
//For Source Vertex : 4 shortest path to other vertices//
0<--1<--3<--4 = 9
1<--3<--4 = 6
2<--4 = 6
3<--4 = 4
4<--4 = 0 Press Enter to continue

Dept. of CSE, KLS VDIT Haliyal. Page 25


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

DESCRIPTION :
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed
edge uv, vertex u comes before v in the ordering.Topological Sorting for a graph is not possible if the graph is
not a DAG. Input parameters: int a[MAX][MAX] - adjacency matrix of the input graph int n - no of vertices in the
graph

ALGORITHM :
L Empty list that will contain the sorted elements S Set of all nodes with no incoming edges while S is non-empty
do remove a node n from S add n to tail of L for each node m with an edge e from n to m do remove edge e
from the graph if m has no other incoming edges then insert m into S if graph has edges then return error
(graph has at least one cycle) else return L (a topologically sorted order)

CODE :
#include <stdio.h>
const int MAX = 10;
void fnTopological(int a[MAX][MAX], int n);
int main(void)
{
int a[MAX][MAX],n;
int i,j;

printf("Topological Sorting Algorithm -\n");


printf("\nEnter the number of vertices : ");
scanf("%d",&n);

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


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

fnTopological(a,n);
printf("\n");
return 0;
}

void fnTopological(int a[MAX][MAX], int n)

Dept. of CSE, KLS VDIT Haliyal. Page 26


Analysis & Design of Algorithms Lab BCSL404
{
int in[MAX], out[MAX], stack[MAX], top=-1;
int i,j,k=0;

for (i=0;i<n;i++)
{
in[i] = 0;
for (j=0; j<n; j++)
if (a[j][i] == 1)
in[i]++;
}

while(1)
{
for (i=0;i<n;i++)
{
if (in[i] == 0)
{
stack[++top] = i;
in[i] = -1;
}
}

if (top == -1)
break;

out[k] = stack[top--];

for (i=0;i<n;i++)
{
if (a[out[k]][i] == 1)
in[i]--;
}
k++;
}

printf("Topological Sorting (JOB SEQUENCE) is:- \n");


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

Dept. of CSE, KLS VDIT Haliyal. Page 27


Analysis & Design of Algorithms Lab BCSL404
printf("%d ",out[i] + 1);
}
OUTPUT
Input Graph : 5 vertices 0 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0

Topological Sorting (JOB SEQUENCE) is:- 2 1 3 4 5

Dept. of CSE, KLS VDIT Haliyal. Page 28


Analysis & Design of Algorithms Lab BCSL404
6. Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic Programming method.

DESCRIPTION:
The Knapsack problem is probably one of the most interesting and most popular in computer science, especially
when we talk about dynamic programming. The knapsack problem is a problem in combinatorial optimization.
Given a set of items, each with a weight and a value, determine the number of each item to include in a
collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill
it with the most valuable items.

ALGORITHM:
Input:
Values (stored in array v or profit)
Weights (stored in array w or weight)
Number of distinct items (n)
Knapsack capacity (W)
for j from 0 to W do
m[0, j] = 0
end for
for i from 1 to n do
for j from 0 to W do
if w[i] <= j then
m[i, j] = max(m[i-1, j], m[i-1, j-w[i]] + v[i])
else
m[i, j] = m[i-1, j]
end if
end for
end for

Program
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX = 10;
inline int max(int a, int b);
void fnProfitTable(int w[MAX], int p[MAX], int n, int c, int t[MAX][MAX]);
void fnSelectItems(int n,int c, int t[MAX][MAX], int w[MAX], int l[MAX]);<\pre>
int main(void)

Dept. of CSE, KLS VDIT Haliyal. Page 29


Analysis & Design of Algorithms Lab BCSL404
{
int i, j, totalProfit;
int weight[MAX];
int profit[MAX];
int capacity;
int num;
int loaded[MAX];
int table[MAX][MAX];
cout<<"Enter the maxium number of objects : ";
cin >> num;
cout << "Enter the weights : \n";
for (i=1; i<=num; i++)
{
cout << "\nWeight " << i << ": ";
cin >> weight[i];
}
cout << "\nEnter the profits : \n";
for (i=1; i<=num; i++)
{
cout << "\nProfit " << i << ": ";
cin >> profit[i];
}
cout << "\nEnter the maximum capacity : ";
cin >> capacity;
totalProfit = 0;
for( i=1; i<=num; i++)
loaded[i] = 0;
fnProfitTable(weight,profit,num,capacity,table);
fnSelectItems(num,capacity,table,weight,loaded);
cout << "Profit Matrix\n";
for (i=0; i<=num; i++)
{
for(j=0; j<=capacity; j++)
{
cout <<"\t"<<table[i][j];
}
cout << endl;
}

Dept. of CSE, KLS VDIT Haliyal. Page 30


Analysis & Design of Algorithms Lab BCSL404
cout << "\nItem numbers which are loaded : \n{ ";
for (i=1; i<=num; i++)
{
if (loaded[i])
{
cout <<i << " ";
totalProfit += profit[i];
}
}
cout << "}" << endl;
cout << "\nTotal Profit : " << totalProfit << endl;
return 0;
}
inline int max(int a, int b)
{
return a>b ? a : b;
}

void fnProfitTable(int w[MAX], int p[MAX], int n, int c, int t[MAX][MAX])


{
int i,j;

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


t[0][j] = 0;

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


t[i][0] = 0;

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


{
for (j=1; j<=c; j++)
{
if (j-w[i] < 0)
t[i][j] = t[i-1][j];
else
t[i][j] = max( t[i-1][j], p[i] + t[i-1][j-w[i]]);
}

Dept. of CSE, KLS VDIT Haliyal. Page 31


Analysis & Design of Algorithms Lab BCSL404
}
}
void fnSelectItems(int n,int c, int t[MAX][MAX], int w[MAX], int l[MAX])
{
int i,j;

i = n;
j = c;

while (i >= 1 && j >= 1)


{
if (t[i][j] != t[i-1][j])
{
l[i] = 1;
j = j - w[i];
i--;
}
else
i--;
}
}
OUTPUT:
Enter the maxium number of objects : 4 Enter the weights :
Weight 1: 2
Weight 2: 1
Weight 3: 3
Weight 4: 2
Enter the profits :
Profit 1: 12
Profit 2: 10
Profit 3: 20
Profit 4: 15
Enter the maximum capacity : 5 Profit Matrix 0 0 0 0 0 0 0 0 12 12 12 12 0 10 12 22 22 22 0 10 12 22 30 32 0 10
15 25 30 37
Item numbers which are loaded : { 1 2 4 }
Total Profit : 37

Dept. of CSE, KLS VDIT Haliyal. Page 32


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.

Program
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;

item_t items[] = {
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", 50, 60, 2},
{"glucose", 15, 60, 2},
{"tin", 68, 45, 3},
{"banana", 27, 60, 3},
{"apple", 39, 40, 3},
{"cheese", 23, 30, 1},
{"beer", 52, 10, 3},
{"suntan cream", 11, 70, 1},
{"camera", 32, 30, 1},
{"T-shirt", 24, 15, 2},
{"trousers", 48, 10, 2},
{"umbrella", 73, 40, 1},
{"waterproof trousers", 42, 70, 1},
{"waterproof overclothes", 43, 75, 1},
{"note-case", 22, 80, 1},
{"sunglasses", 7, 20, 1},
{"towel", 18, 12, 2},
{"socks", 4, 50, 1},
{"book", 30, 10, 2},
};

Dept. of CSE, KLS VDIT Haliyal. Page 33


Analysis & Design of Algorithms Lab BCSL404

int n = sizeof (items) / sizeof (item_t);

int *knapsack (int w) {


int i, j, k, v, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
m[i][j] = m[i - 1][j];
for (k = 1; k <= items[i - 1].count; k++) {
if (k * items[i - 1].weight > j) {
break;
}
v = m[i - 1][j - k * items[i - 1].weight] + k * items[i - 1].value;
if (v > m[i][j]) {
m[i][j] = v;
}
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
int v = m[i][j];
for (k = 0; v != m[i - 1][j] + k * items[i - 1].value; k++) {
s[i - 1]++;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}

int main () {
int i, tc = 0, tw = 0, tv = 0, *s;

Dept. of CSE, KLS VDIT Haliyal. Page 34


Analysis & Design of Algorithms Lab BCSL404
s = knapsack(400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf("%-22s %5d %5d %5d\n", items[i].name, s[i], s[i] * items[i].weight, s[i] * items[i].value);
tc += s[i];
tw += s[i] * items[i].weight;
tv += s[i] * items[i].value;
}
}
printf("%-22s %5d %5d %5d\n", "count, weight, value:", tc, tw, tv);
return 0;
}
Output:
map 1 9 150
compass 1 13 35
water 1 153 200
glucose 2 30 120
banana 3 81 180
cheese 1 23 30
suntan cream 1 11 70
waterproof overclothes 1 43 75
note-case 1 22 80
sunglasses 1 7 20
socks 1 4 50
count, weight, value: 14 396 1010

Dept. of CSE, KLS VDIT Haliyal. Page 35


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.

Desrcription:
In computer science, the subset sum problem is an important problem in complexity theory and cryptography.
The problem is this: Given a set of integers, is there a non-empty subset whose sum is zero? For example, given
the set {-7, -3, -2, 5, 8}, the answer is yes because the subset {-3, -2, 5} sums to zero. The problem is NP-
complete. Input: The number of elements. The Weights of each element. Total Required Weight.
Output:Subsets in which the sum of elements is equal to the given required weight(input).

Program
#include <iostream>
using namespace std;

// Constant definitions
const int MAX = 100;

// class definitions
class SubSet
{
int stk[MAX], set[MAX];
int size, top, count;
public:
SubSet()
{
top = -1;
count = 0;
}
void getInfo(void);
void push(int data);
void pop(void);
void display(void);
int fnFindSubset(int pos, int sum);
};
void SubSet :: getInfo(void)
{
int i;
cout << "Enter the maximum number of elements : ";

Dept. of CSE, KLS VDIT Haliyal. Page 36


Analysis & Design of Algorithms Lab BCSL404
cin >> size;

cout << "Enter the weights of the elements : \n";


for (i=1; i<=size; i++)
cin >> set[i];
}
void SubSet :: push(int data)
{
stk[++top] = data;
}
void SubSet :: pop(void)
{
top--;
}
void SubSet :: display()
{
int i;
cout << "\nSOLUTION #"<< ++count <<" IS\n{ ";
for (i=0; i<=top; i++)
cout << stk[i] << " ";
cout << "}" << endl;
}
int SubSet :: fnFindSubset(int pos, int sum)
{
int i;
static int foundSoln = 0;

if (sum>0)
{
for (i=pos; i<=size; i++)
{
push(set[i]);
fnFindSubset(i+1, sum - set[i]);
pop();
}
}
if (sum == 0)
{

Dept. of CSE, KLS VDIT Haliyal. Page 37


Analysis & Design of Algorithms Lab BCSL404
display();
foundSoln = 1;
}
return foundSoln;
}
int main(void)
{
int i,sum;
SubSet set1;
set1.getInfo();
cout << "Enter the total required weight : ";
cin >> sum;
cout << endl;
if (!set1.fnFindSubset(1, sum))
cout << "\n\nThe given problem instance doesnt have any solution." << endl;
else
cout << "\n\nThe above-mentioned sets are the required solution to the given instance." << endl;
return 0;
}
OUTPUT
SAMPLE 1
Enter the maximum number of elements : 5
Enter the weights of the elements :
12345
Enter the total required weight : 5
SOLUTION #1 IS
{14}
SOLUTION #2 IS
{23}
SOLUTION #3 IS
{5}
The above-mentioned sets are the required solution to the given instance.
SAMPLE 2
Enter the maximum number of elements : 4
Enter the weights of the elements :
1234
Enter the total required weight : 11
The given problem instance doesnt have any solution.

Dept. of CSE, KLS VDIT Haliyal. Page 38


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

Algorithm
SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT
SMALLEST (arr, i, n, pos)
Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos

Program
#include <stdio.h>
void selection_sort (int *a, int n) {
int i, j, m, t;
for (i = 0; i < n; i++) {
for (j = i, m = i; j < n; j++) {
if (a[j] < a[m]) {
m = j;
}
}
t = a[i];
a[i] = a[m];
a[m] = t;
}

Dept. of CSE, KLS VDIT Haliyal. Page 39


Analysis & Design of Algorithms Lab BCSL404
}

int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
selection_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
Output:
Input : 4 65 2 -31 0 99 2 83 782 1
Output: -31 0 1 2 2 4 65 83 99 782

Dept. of CSE, KLS VDIT Haliyal. Page 40


Analysis & Design of Algorithms Lab BCSL404

Comparison with other sorting algorithms


Algorithm Sort Algorithm Average Time Best Time Worst

Selection Sort O(n2) O(n2) O(n2)

Insertion Sort O(n2) O(n) O(n2)

Heap Sort O(n*log(n)) O(n*log(n)) O(n*log(n))

Merge Sort O(n*log(n)) O(n*log(n)) O(n*log(n))

Quick Sort O(n*log(n)) O(n*log(n)) O(n2)

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.

Description:
The program is based on the Quicksort algorithm which is an instantiation of divide and conquer method of
solving the problem. Here the given array is partitioned every time and the sub-array is sorted. Dividing is based
on an element called pivot. A divide and conquer algorithm works by recursively breaking down a problem into
two or more sub-problems of the same (or related) type, until these become simple enough to be solved
directly. The solutions to the sub-problems are then combined to give a solution to the original problem.
Dept. of CSE, KLS VDIT Haliyal. Page 41
Analysis & Design of Algorithms Lab BCSL404

Program
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

void fnGenRandInput(int [], int);


void fnDispArray( int [], int);
int fnPartition(int [], int , int );
void fnQuickSort(int [], int , int );
inline void fnSwap(int*, int*);

inline void fnSwap(int *a, int *b)


{
int t = *a; *a = *b; *b = t;
}
int main( int argc, char **argv)
{

FILE *fp;
struct timeval tv;
double dStart,dEnd;
int iaArr[500000],iNum,iPos,iKey,i,iChoice;

for(;;)
{
printf("\n1.Plot the Graph\n2.QuickSort\n3.Exit");
printf("\nEnter your choice\n");
scanf("%d",&iChoice);

switch(iChoice)
{
case 1:
fp = fopen("QuickPlot.dat","w");

for(i=100;i<100000;i+=100)
{
fnGenRandInput(iaArr,i);

gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);

Dept. of CSE, KLS VDIT Haliyal. Page 42


Analysis & Design of Algorithms Lab BCSL404

fnQuickSort(iaArr,0,i-1);

gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);

fprintf(fp,"%d\t%lf\n",i,dEnd-dStart);

}
fclose(fp);

printf("\nData File generated and stored in file < QuickPlot.dat >.\n Use a plotting utility\n");
break;

case 2:
printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(iaArr,iNum);
fnDispArray(iaArr,iNum);
fnQuickSort(iaArr,0,iNum-1);
printf("\nSorted Array\n");
fnDispArray(iaArr,iNum);
break;

case 3:
exit(0);
}
}

return 0;
}

int fnPartition(int a[], int l, int r)


{
int i,j,temp;
int p;

p = a[l];
i = l;
j = r+1;

do
{
Dept. of CSE, KLS VDIT Haliyal. Page 43
Analysis & Design of Algorithms Lab BCSL404
do { i++; } while (a[i] < p);
do { j--; } while (a[j] > p);

fnSwap(&a[i], &a[j]);
}
while (i<j);

fnSwap(&a[i], &a[j]);
fnSwap(&a[l], &a[j]);

return j;
}

void fnQuickSort(int a[], int l, int r)


{
int s;

if (l < r)
{
s = fnPartition(a, l, r);
fnQuickSort(a, l, s-1);
fnQuickSort(a, s+1, r);
}
}

void fnGenRandInput(int X[], int n)


{
int i;

srand(time(NULL));
for(i=0;i<n;i++)
{
X[i] = rand()%10000;
}

void fnDispArray( int X[], int n)


{
int i;

for(i=0;i<n;i++)
printf(" %5d \n",X[i]);

Dept. of CSE, KLS VDIT Haliyal. Page 44


Analysis & Design of Algorithms Lab BCSL404
}

OUTPUT:

Dept. of CSE, KLS VDIT Haliyal. Page 45


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.

DESCRIPTION:
Merge sort is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort,
meaning that the implementation preserves the input order of equal elements in the sorted output. It is a divide
and conquer algorithm.

ALGORITHM:
Mergesort(A[O .. n - 1])
Sorts array A[O .. n - 1] by recursive mergesort
Input: An array A[O .. n - 1] of orderable elements
Output: Array A[O .. n - 1] sorted in nondecreasing order
Merge(B[O .. p- 1], C[O .. q -1], A[O.. p + q -1])
Merges two sorted arrays into one sorted array
Input: Arrays B[O .. p -1] and C[O .. q -1] both sorted
Output: Sorted array A[O .. p + q -1] of the elements of Band C
Program
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <omp.h>

void simplemerge(int a[], int low, int mid, int high)


{
int i,j,k,c[20000];
i=low;
j=mid+1;
k=low;
int tid;
omp_set_num_threads(10);
{
tid=omp_get_thread_num();
while(i<=mid&&j<=high)
{

Dept. of CSE, KLS VDIT Haliyal. Page 46


Analysis & Design of Algorithms Lab BCSL404
if(a[i] < a[j])
{
c[k]=a[i];
//printf("%d%d",tid,c[k]);
i++;
k++;
}
else
{
c[k]=a[j];
//printf("%d%d", tid, c[k]);
j++;
k++;
}
}
}
while(i<=mid)
{
c[k]=a[i];
i++;
k++;
}
while(j<=high)
{
c[k]=a[j];
j++;
k++;
}
for(k=low;k<=high;k++)
a[k]=c[k];
}

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


{
int mid;
if(low < high)
{
mid=(low+high)/2;

Dept. of CSE, KLS VDIT Haliyal. Page 47


Analysis & Design of Algorithms Lab BCSL404
merge(a,low,mid);
merge(a,mid+1,high);
simplemerge(a,low,mid,high);
}
}

void getnumber(int a[], int n)


{
int i;
for(i=0;i < n;i++)
a[i]=rand()%100;
}

int main()
{
FILE *fp;
int a[2000],i;
struct timeval tv;
double start, end, elapse;
fp=fopen("mergesort.txt","w");
for(i=10;i<=1000;i+=10)
{
getnumber(a,i);
gettimeofday(&tv,NULL);
start=tv.tv_sec+(tv.tv_usec/1000000.0);
merge(a,0,i-1);
gettimeofday(&tv,NULL);
end=tv.tv_sec+(tv.tv_usec/1000000.0);
elapse=end-start;
fprintf(fp,"%d\t%lf\n",i,elapse);
}
fclose(fp);
system("gnuplot");
return 0;
}

Dept. of CSE, KLS VDIT Haliyal. Page 48


Analysis & Design of Algorithms Lab BCSL404
mergesort.gpl
Gnuplot script file for plotting data in file "mergesort.txt" This file is called mergesort.gpl
set terminal png font arial
set title "Time Complexity for Merge Sort"
set autoscale
set xlabel "Size of Input"
set ylabel "Sorting Time (microseconds)"
set grid
set output "mergesort.png"
plot "mergesort.txt" t "Merge Sort" with lines

OUTPUT

Dept. of CSE, KLS VDIT Haliyal. Page 49


Analysis & Design of Algorithms Lab BCSL404

Dept. of CSE, KLS VDIT Haliyal. Page 50


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

Dept. of CSE, KLS VDIT Haliyal. Page 51


Analysis & Design of Algorithms Lab BCSL404

/*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)
{
//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);
}
}
}

Dept. of CSE, KLS VDIT Haliyal. Page 52


Analysis & Design of Algorithms Lab BCSL404
Output :

0 0 1 0

1 0 0 0

0 0 0 1

0 1 0 0

Dept. of CSE, KLS VDIT Haliyal. Page 53


Analysis & Design of Algorithms Lab BCSL404

Virtual Lab

1. Depth First Search


Learning Objectives of the Experiment

In this experiment, we will be learn about:

1. Understand the basics of graphs and their representations.


2. Understand the working of Depth First Traversal Algorithm for searching nodes.
3. Given a graph, understand the progression of the Depth First Traversal Algorithm and search for
particular nodes.
4. Demonstrate the knowledge of time complexity of the Depth First Search Traversal algorithm.

Definition

A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The
interconnected objects are represented by points termed as vertices, and the links that connect the vertices are
called edges.

Undirected Graph

Directed Graph

Dept. of CSE, KLS VDIT Haliyal. Page 54


Analysis & Design of Algorithms Lab BCSL404

Dept. of CSE, KLS VDIT Haliyal. Page 55


Analysis & Design of Algorithms Lab BCSL404
Breadth First Search

Learning Objectives of the Experiment

In this experiment, we will be able to do the following:

1. Study the basic concepts of Graphs and Queues and their representation.
2. Study the various Graph traversal algorithms and difference between them.
3. Understand the BFS Graph traversal using queues.
4. Demonstrate knowledge of time complexity and space complexity of performing a BFS on a given graph.

Definition
Breadth First Search (BFS) is a technique for traversing a finite graph. BFS visits the neighbour vertices before
visiting the child vertices, and a queue is used in the search process. This algorithm is often used to find the
shortest path from one vertex to another.

Here we start traversing from a selected node (source node) and traverse the graph layer/level wise thus
exploring the neighbour nodes (nodes which are directly connected to source node). We must move to the next
layer/level only after traversing the current layer/level completely.

Dept. of CSE, KLS VDIT Haliyal. Page 56


Analysis & Design of Algorithms Lab BCSL404

Dept. of CSE, KLS VDIT Haliyal. Page 57

You might also like