Daa Labmanual 2024-25
Daa Labmanual 2024-25
LABORATORY MANUAL
SEMESTER :IV
SUBJECT :Analysis&Design ofAlgorithmsLab
SUBCODE :BCSL404
NAME:____________________________________________________________
USN: _____________________________________________________________
SECTION:__________________________________________________________
BATCH:___________________________________________________________
PROGRAM OUTCOMES
Engineering Graduates will able to:
Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern 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, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice. Individual and team work: Function effectively as an
individual, and as a member or leader in diverse teams, and in multidisciplinary settings.
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.
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.
INSTITUTE VISION AND MISSION
VISION
MISSION
VISION
The department orients towards identifying and exploring emerging global trends in
the fields of Artificial Intelligence and Data Science through academic excellence
and quality research, producingproficient professionals for a flourishing society.
MISSION
M1: To nurture students with quality education, life-long learning, values and
ethics.
M2:To produce ethical and competent professionals through comprehensive and
holistic methodologies that align with the global industry demands in Artificial
Intelligence and Data Science.
1. To cater and enhance the analytical and technical skills of the graduates in
order to be ready for the professional development, research and pursue
higher education.
2. To formulate solutions for the real-world problems with the application of
basic engineering principles and technical skills of Artificial Intelligence
and Data Science.
Analysis&Design ofAlgorithmsLab Semester 4
CourseCode BCSL404 CIEMarks 50
TeachingHours/Week(L:T:P:S) 0:0:2:0 SEEMarks 50
Credits 01 ExamHours 2
Examinationtype(SEE) Practical
Courseobjectives:
● TodesignandimplementvariousalgorithmsinC/C++programmingusingsuitabledevelopmenttoolstoaddressdiffere
ntcomputational challenges.
● Toapplydiversedesignstrategiesforeffectiveproblem-solving.
● ToMeasureandcomparetheperformanceofdifferentalgorithmstodeterminetheirefficiencyandsuitabilityforspecifictasks
.
Sl.No Experiments
1 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof agivenconnected
undirectedgraphusingKruskal'salgorithm.
2 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof agivenconnected
undirectedgraphusingPrim'salgorithm.
3 a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd'salgorithm.
b. DesignandimplementC/C++ProgramtofindthetransitiveclosureusingWarshal's
algorithm.
4 DesignandimplementC/C++Programtofindshortestpathsfromagivenvertexinaweighted
connectedgraphtootherverticesusingDijkstra'salgorithm.
5 DesignandimplementC/C++ProgramtoobtaintheTopologicalorderingofverticesinagiven
digraph.
6 DesignandimplementC/C++Programtosolve0/1KnapsackproblemusingDynamic
Programmingmethod.
7 DesignandimplementC/C++ProgramtosolvediscreteKnapsackandcontinuousKnapsack
problemsusinggreedyapproximationmethod.
8 DesignandimplementC/C++ProgramtofindasubsetofagivensetS={sl,s2,.....,sn}ofn
positiveintegerswhosesumisequaltoagivenpositiveintegerd.
9 Design and implement C/C++ Program to sort a given set of n integer elements using SelectionSort
method and compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
10 Design and implement C/C++ Program to sort a given set of n integer elements using Quick
Sortmethod and compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanbereadfromafileorcanb
egeneratedusingthe randomnumbergenerator.
11 Design and implement C/C++ Program to sort a given set of n integer elements using Merge
Sortmethod and compute its time complexity. Run the program for varied values of n> 5000,
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanbereadfromafileorcanb
egeneratedusingthe random numbergenerator.
12 DesignandimplementC/C++ProgramforNQueen'sproblemusingBacktracking.
Courseoutcomes(CourseSkillSet):
Attheendofthecoursethe studentwillbeableto:
1. Developprogramstosolvecomputationalproblemsusingsuitablealgorithmdesignstrategy.
2. Compare algorithmdesign strategiesby developing equivalent programsandobservingrunningtimes
foranalysis(Empirical).
3. Makeuseofsuitableintegrateddevelopmenttoolstodevelopprograms
4. Chooseappropriatealgorithmdesigntechniquestodevelopsolutiontothecomputationalandcomplexproble
ms.
5. Demonstrateandpresentthedevelopmentofprogram,itsexecutionandrunningtime(s)and
recordtheresults/inferences.
AssessmentDetails(bothCIEandSEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for theSEE
minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall bedeemed to have
satisfied the academic requirements and earned the credits allotted to each subject/course if the student secures
a minimum of 40% (40 marks out of 100) in the sum total of the CIE(Continuous
InternalEvaluation)andSEE(SemesterEndExamination)takentogether
ContinuousInternalEvaluation(CIE):
CIEmarksforthepracticalcourseare50Marks.
Thesplit-upofCIEmarksforrecord/journalandtestareintheratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-
up.Rubrics for the evaluation of the journal/write-up for hardware/software experiments aredesigned by
the faculty who is handling the laboratory session and are made known to students atthebeginningof the
practicalsession.
● Record should contain all the specified experiments in the syllabus and each experiment write-
upwillbeevaluated for10 marks.
● Totalmarksscoredbythestudentsarescaleddownto 30marks(60%ofmaximummarks).
● Weightagetobegivenforneatnessandsubmissionofrecord/write-upontime.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed
inthesyllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge
willcarryaweightageof60%andtherest40% forviva-voce.
● Thesuitablerubricscanbedesignedtoevaluateeachstudent’sperformanceandlearningability.
● Themarks scoredshallbescaleddownto 20marks(40%ofthemaximummarks).
The Sumofscaled-downmarksscoredinthereportwrite-up/journalandmarksofatest isthetotalCIEmarks scored
bythestudent.
SemesterEndEvaluation(SEE):
● SEEmarksforthepracticalcourseare50Marks.
● SEEshallbeconductedjointlybythetwoexaminersofthesameinstitute,examinersareappointedbytheHeadoft
heInstitute.
● The examination schedule and names of examiners are informed to the university before theconduction
of the examination. These practical examinations are to be conducted between
theschedulementionedinthe academiccalendarof theUniversity.
● Alllaboratoryexperimentsaretobeincludedforpracticalexamination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer scriptto be
strictly adhered to by the examiners.OR based on the course requirement evaluationrubricsshallbe
decidedjointlybyexaminers.
● Students can pick one question (experiment) from the questions lot prepared by the examinersjointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly
byexaminers.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure andresult in -
60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marksand scored
marks shall be scaled down to 50 marks (however, based on course type, rubrics shall bedecidedbythe
examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to
bemadezero.
TheminimumdurationofSEEis02hours
SuggestedLearningResources:
● VirtualLabs(CSE):http://cse01-iiith.vlabs.ac.in/
Index
SI. Page
ProgramsList: CO PO RBT No.
No.
1 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof
agivenconnectedundirectedgraphusingKruskal'salgorithm. CO1 PO2 L2 4
2 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof
agivenconnectedundirectedgraphusingPrim'salgorithm. CO1 PO2 L2 7
b. DesignandimplementC/C++ProgramtofindthetransitiveclosureusingWarshal
'salgorithm. CO1 PO3 L2 15
4. DesignandimplementC/C++Programtofindshortestpathsfromagivenvertexi
naweightedconnectedgraphtootherverticesusingDijkstra'salgorithm. CO1 PO3 L3 18
5. DesignandimplementC/C++ProgramtoobtaintheTopologicalorderingofvert
icesinagivendigraph.
CO1 PO3 L3 20
6. DesignandimplementC/C++Programtosolve0/1KnapsackproblemusingDyn
amicProgrammingmethod. CO2 PO3 L4 24
DesignandimplementC/C++ProgramtosolvediscreteKnapsackandcontinuo
7. usKnapsackproblemsusinggreedyapproximationmethod. CO2
PO3 L4 29
8. DesignandimplementC/C++ProgramtofindasubsetofagivensetS={sl,s2,....., CO3
sn}ofnpositiveintegerswhosesumisequaltoagivenpositiveintegerd. PO3 L3 34
PROGRAMS
DEPTOFAI&DS,EPCET Page1
DesignandanalysisofAlgorithms 21CS42
WhatisAlgorithm?
A finite set of instruction that specifies a sequence of operation is to be carried out in order
tosolve a specific problemorclass ofproblemsiscalledanAlgorithm.
WhystudyAlgorithm?
Asthespeedofprocessorincreases,performanceisfrequentlysaidtobelesscentralthanothersoftwar
equalitycharacteristics(e.g.security,extensibility,reusabilityetc.).However,largeproblemsizesar
ecommonplaceintheareaofcomputationalscience,whichmakesperformanceavery
importantfactor.Thisisbecauselongercomputation
time,tonameafewmeanslowerresults,ThestudyofAlgorithm,therefore,givesusalanguagetoexpre
ssperformance as afunctionofproblemsize.
Analgorithmmusthavethefollowi
ngproperties:
o Correctness:Itshouldproducetheoutputaccordingtotherequirementofthealgorit
hm
o Finiteness:Algorithmmustcompleteafterafinite
numberofinstructionshavebeenexecuted.
o Definiteness:Eachstepmustbedefined,havingonlyoneinterpretation.
o Input/output:Numberandclassificationofneededinputsandresults mustbestated.
o Feasibility:Itmustbefeasibleto executeeachinstruction.
o Flexibility:Itshouldalsobepossibletomakechangesinthealgorithmwithoutputtingsomuc
heffortonit.
o Efficient-Efficiencyisalwaysmeasuredintermsoftimeandspacerequiresimplementing
the algorithm, so the algorithm uses a little running time and memoryspace aspossible
withinthelimitsofacceptable developmenttime.
ComplexityofAlgorithm
Space Complexity: Some forms of analysis could be done based on how much space
analgorithm needs to complete its task. This space complexity analysis was critical in the
earlydaysofcomputingwhenstoragespaceonthe computerwas limited.
Thefollowing aretetypesofanalysis
, Page2
AlgorithmDesignTechniques
Thefollowingisalistofseveralpopulardesignapproaches:
1. Divide and Conquer Approach: It is a top-down approach. The algorithms which followthe
divide&conquertechniquesinvolve threesteps:
o Dividetheoriginalproblemintoasetofsubproblems.
o Solveeverysubproblemindividually,recursively.
o Combinethesolutionofthesubproblems(toplevel)intoasolutionof
thewholeoriginalproblem.
#include<iostream>
#include<string.h>
using namespace std;
class Graph
{
char vertices[10][10];
int cost[10][10],no;
public:
Graph();
void creat_graph();
void display();
int Position(char[]);
void kruskal_algo();
};
/* Initialzing adj matrix with 999 */
/* 999 denotes infinite distance */
Graph::Graph()
{
no=0;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
cost[i][j]=999;
}
}
/* Taking inputs for creating graph */
void Graph::creat_graph()
{
char ans,Start[10],End[10];
int wt,i,j;
cout<<"Enter the number of vertices: ";
cin>>no;
cout<<"\nEnter the vertices: ";
for(i=0;i<no;i++)
cin>>vertices[i];
do
{
cout<<"\nEnter Start and End vertex of the edge: ";
cin>>Start>>End;
cout<<"Enter weight: ";
cin>>wt;
i=Position(Start);
j=Position(End);
cost[i][j]=cost[j][i]=wt;
cout<<"\nDo you want to add more edges (Y=YES/N=NO)? : "; /* Type 'Y' or 'y' for YES and 'N' or 'n' for
NO */
cin>>ans;
}while(ans=='y' || ans=='Y');
}
/* Displaying Cost matrix */
void Graph::display()
{
int i,j;
cout<<"\n\nCost matrix: ";
for(i=0;i<no;i++)
{
cout<<"\n";
for(j=0;j<no;j++)
cout<<"\t"<<cost[i][j];
}
}
/* Retrieving position of vertices in 'vertices' array */
int Graph::Position(char key[10])
{
int i;
for(i=0;i<10;i++)
if(strcmp(vertices[i],key)==0)
return i;
return -1;
}
void Graph::kruskal_algo()
{
int i,j,v[10]={0},x,y,Total_cost=0,min,gr=1,flag=0,temp,d;
while(flag==0)
{
min=999;
for(i=0;i<no;i++)
{
for(j=0;j<no;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
x=i;
y=j;
}
}
}
cost[x][y]=cost[y][x]=999;
Total_cost=Total_cost+min; /* calculating cost of minimum spanning tree */
cout<<"\n\t"<<vertices[x]<<"\t\t"<<vertices[y]<<"\t\t"<<min;
temp=v[0]; flag=1;
for(i=0;i<no;i++)
{
if(temp!=v[i])
{
flag=0;
break;
}
}
}
cout<<"\nTotal cost of the tree= "<<Total_cost;
}
int main()
{
Graph g;
g.creat_graph();
g.display();
cout<<"\n\n\nMinimum Spanning tree using kruskal algo=>";
cout<<"\nSource vertex\tDestination vertex\tWeight\n";
g.kruskal_algo();
return 0;
}
OUTPUT
Cost matrix:
999 2 999 6 999
2 999 3 8 5
999 3 999 999 7
6 8 999 999 9
999 5 7 9 999
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 main()
{
int cost[10][10],visited[10]={0},i,j,n,no_e=1,min,a,b,min_cost=0;
printf("Enter number of nodes ");
scanf("%d",&n);
printf("Enter cost in form of adjacency matrix\n");
//input graph
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
// cost is 0 then initialize it by maximum value
if(cost[i][j]==0)
cost[i][j]=1000;
}
}
Output:-
1 to 2 cost=4
2 to 3 cost=2
3 to 5 cost=2
3 to 4 cost=3
4 to 6 cost=3
minimum weight is 14
3.a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's algorithm.
#include <iostream>
#include <cstdlib>
#define max 10
#define infi 999
using namespace std;
int p[max][max];
/*
* All Pairs Shortest Path using Floyd's Algorithm
*/
void allpairshort(int a[max][max], int n)
{
int k, i, j;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i][k] + a[k][j] < a[i][j])
{
a[i][j] = a[i][k] + a[k][j];
p[i][j] = k;
}
}
}
}
}
/*
* Storing the shortest path
*/
void shortest(int i, int j)
{
int k = p[i][j];
if (k > 0)
{
shortest(i, k);
cout<<" "<<k<<" ";
shortest(k, j);
}
}
/*
* Display the Shortest Path
*/
void findpath(int a[max][max], int i, int j, int n)
{
cout<<"Path from " << i <<" to "<< j << ":";
if (a[i][j] < infi)
{
cout<<" "<<i<<" ";
shortest(i, j);
cout<<" "<<j<<" ";
}
}
/*
* Main Contains Menu
*/
int main()
{
int i, j;
int a[][10] = {{0, 10, infi, 30, 100},
{infi, 0 , 50, infi, infi},
{infi, infi , 0, infi, 10},
{infi, infi , 20, 0, 60},
{infi, infi , infi, infi, 0},
};
allpairshort(a, 5);
findpath(a, 0, 4, 5);
return 0;
}
Output
Path from 0 to 4: 0 3 2 4
3b.Design and implement C/C++ Program to find the transitive closure using Warshal's algorithm.
#include<iostream>
int main()
{
int num_nodes, k, n;
char i, j, res, c;
int adj[10][10], path[10][10];
c = 65 + i;
cout << "\t\t\t" << c << " ";
for (int j = 0; j < num_nodes; j++)
cout << adj[i][j] << " ";
cout << "\n";
}
return 0;
}
Output
Maximum number of nodes in the graph :4
Adjacency Matrix:
ABCD
A 1010
B 0111
C 1011
D 0111
ABCD
A 1111
B 1111
C 1111
D 1111
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 <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false &&dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i< V; i++)
printf("%d \t %d\n", i, dist[i]);
return 0;
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i< V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] &&dist[u] != INT_MAX &&dist[u] + graph[u][v] <dist[v]) dist[v] = dist[u] +
graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}
Output
Vertex Distance from Source
00
16
2 14
3 21
4 21
5 11
69
78
8 15
5.Design and implement C/C++ Program to obtain the Topological ordering of vertices in a given digraph
#include <stdio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}
Output
6.Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic Programming method.
#include<stdio.h>
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
for (i = 0; i<= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int main()
{
int i, n, val[20], wt[20], W;
Output
7. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack problems using greedy
approximation method.
struct Item {
int weight;
int value;
double ratio; // value-to-weight ratio
return totalValue;
}
int main() {
int capacity;
cout<< "Enter the capacity of the knapsack: ";
cin>> capacity;
int n;
cout<< "Enter the number of items: ";
cin>> n;
vector<Item> items;
cout<< "Enter weight and value for each item:\n";
for (int i = 0; i< n; ++i) {
int weight, value;
cin>> weight >> value;
items.push_back(Item(weight, value));
}
double maxValue = fractionalKnapsack(capacity, items);
cout<< "Maximum value that can be obtained: " <<maxValue<<endl;
return 0;
}
Output
b.
#include <iostream>
#include <vector>
#include <algorithm>
struct Item {
int weight;
int value;
int totalValue = 0;
for (const auto &item : items) {
if (capacity == 0)
break;
if (item.weight<= capacity) {
totalValue += item.value;
capacity -= item.weight;
}
}
return totalValue;
}
int main() {
int capacity;
cout<< "Enter the capacity of the knapsack: ";
cin>> capacity;
int n;
cout<< "Enter the number of items: ";
cin>> n;
vector<Item> items;
cout<< "Enter weight and value for each item:\n";
for (int i = 0; i< n; ++i) {
int weight, value;
cin>> weight >> value;
items.push_back(Item(weight, value));
}
return 0;
}
Output
Enter the number of items: 5
Enter weight and value for each item:
10 60
20 100
30 120
5 50
15 70
Maximum value that can be obtained: 330
8. Design and implement c/c++ program to find a subset of a given set S={s1,s2,...,sn} of n positive integer whose sum is
equal to given positive integer d
#include<stdio.h>
#include<stdlib.h>
staticinttotal_nodes;
voidprintValues(int A[],int size){
for(inti=0;i< size;i++){
printf("%*d",5, A[i]);
}
printf("\n");
}
voidsubset_sum(int s[],int t[],ints_size,intt_size,int
sum,intite,intconsttarget_sum){
total_nodes++;
if(target_sum== sum){
printValues(t,t_size);
subset_sum(s, t,s_size,t_size-1, sum -
s[ite],ite+1,target_sum);
return;
}
else{
for(inti=ite;i<s_size;i++){
t[t_size]= s[i];
subset_sum(s, t,s_size,t_size+1, sum +
s[i],i+1,target_sum);
}
}
}
voidgenerateSubsets(int s[],int size,inttarget_sum){
int*tuplet_vector=(int*)malloc(size *sizeof(int));
subset_sum(s,tuplet_vector, size,0,0,0,target_sum);
free(tuplet_vector);
}
intmain(){
intset[]={5,6,12,54,2,20,15};
int size =sizeof(set)/sizeof(set[0]);
printf("The set is ");
printValues(set, size);
generateSubsets(set, size,25);
printf("Total Nodes generated %d\n",total_nodes);
return0;
}
Output
The set is 5 6 12 54 2 20 15
5 6 12 2
5 20
Total Nodes generated 127
9.Design and implement C/C++ Program to sort a given set of n integer elements using SelectionSort method and
compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
#include <bits/stdc++.h>
usingnamespacestd;
//Swap function
voidswap(int*xp, int*yp)
{
inttemp = *xp;
*xp = *yp;
*yp = temp;
}
voidselectionSort(intarr[], intn)
{
inti, j, min_idx;
Output
Sorted array:
11 12 22 25 64
10.Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sortmethod and
compute its time complexity. Run the program for varied values of n> 5000,
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe random numbergenerator.
// C++ program for Merge Sort
#include <iostream>
usingnamespacestd;
// UTILITY FUNCTIONS
// Function to print an array
voidprintArray(intA[], intsize)
{
for(autoi = 0; i< size; i++)
cout<< A[i] <<" ";
cout<<endl;
}
// Driver code
intmain()
{
intarr[] = { 12, 11, 13, 5, 6, 7 };
autoarr_size = sizeof(arr) / sizeof(arr[0]);
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
11.Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sortmethod and
compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
// Quick sort in C++
#include <iostream>
using namespace std;
// Driver code
int main() {
int data[] = {8, 7, 6, 1, 0, 9, 2};
int n = sizeof(data) / sizeof(data[0]);
Output
Unsorted Array:
8761092
Sorted array in ascending order:
0126789
12.DesignandimplementC/C++ProgramforNQueen'sproblemusingBacktracking.
#include <bits/stdc++.h>
#define N 4
using namespace std;
return true;
}
if (solveNQUtil(board, 0) == false) {
cout<< "Solution does not exist";
return false;
}
printSolution(board);
return true;
}
solveNQ();
return 0;
}
Output
. . Q .
Q . . .
. . . Q
. Q . .