DAA Lab Manual - 21cs42-Final
DAA Lab Manual - 21cs42-Final
ENGINEERING
IV SEMESTER
LABORATORY MANUAL
Programs List:
1. 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.
Demonstrate using C++/Java how the brute force method works along with its time complexity analysis:
worst case, average case and best case.
2. 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.
Demonstrate using C++/Java how the divide-and-conquer method works along with its time complexity
analysis: worst case, average case and best case.
3. 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.
Demonstrate using C++/Java how the divide-and-conquer method works along with its time complexity
analysis: worst case, average case and best case.
4. Write & Execute C++/Java Program To solve Knapsack problem using Greedy method
5. Write & Execute C++/Java Program To find shortest paths to other vertices from a given vertex in a
weighted connected graph, using Dijkstra's algorithm.
6. Write & Execute C++/Java Program To find Minimum Cost Spanning Tree of a given connected undirected
graph using Kruskal's algorithm. Use Union-Find algorithms in your program.
7. Write & Execute C++/Java Program To find Minimum Cost Spanning Tree of a given connected undirected
graph using Prim's algorithm.
8. Write C++/ Java programs to Solve All-Pairs Shortest Paths problem using Floyd's algorithm.
9. Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic programming.
10. Write C++/ Java programs to Solve 0/1 Knapsack problem using Dynamic Programming method.
11. Design and implement C++/Java Program to find a subset of a given set S = {Sl, S2,…, Sn} of npositive
integers whose SUM is equal to a given positive integer d. For example, if S = {1, 2, 5, 6, 8} and d= 9, there
are two solutions {1, 2, 6} and {1, 8}. Display a suitable message, if the given problem instance doesn't
have a solution.
12. Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected undirected Graph G
of n vertices using backtracking principle.
M1. To impart quality education in Computer Science and Engineering with the strong
industry institute partnership to develop technical & research skills.
M2. Enrich the technical ability of students to face the world with confidence,
commitment and team-work in IT field.
M3. Provide a learning platform for interdisciplinary innovation, research and Self-
learning.
M4. Encourage faculty and students to actively participate in holistic educational
practices and to impart social values.
Program Educational Objectives (PEOs)
Graduates develop knowledge in the core areas of Computer Science Engineering and
PEO 1 enhance technical and research skills for providing software solutions
Graduates will pursue technical and managerial skills to analyze and develop problem
PEO 2 solving abilities of Computer Science and Engineering through Mathematics, Science
and Engineering to encounter industrial needs.
Graduates develop effective communication and management skills to interact
PEO 3 effectively with stakeholders in the field of Computer Science Engineering and develop
innovative solutions for real time problems.
Graduates with Lifelong learning demonstrate skills and knowledge in the domain of
PEO 4 computer programming and exhibit leadership qualities, team work, social and ethical
values.
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and design
PO3 system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8
engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9
teams, and in multidisciplinary settings.
Course outcomes:
CO Statement
No.
C42.1 Analyze the performance of the algorithms, state the efficiency using asymptotic
notations and analyze mathematically the complexity of the algorithm.
C42.2 Apply divide and conquer approaches and decrease and conquer approaches in solving
the problems analyze the same
C42.3 Apply the appropriate algorithmic design technique like greedy method, transform and
conquer approaches and compare the efficiency of algorithms to solve the given
problem.
C42.4 Apply and analyze dynamic programming approaches to solve some problems. and
improve an algorithm time efficiency by sacrificing space.
C42.5 Apply and analyze backtracking, branch and bound methods and to describe P, NP and
NP-Complete problems.
1. 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.
Demonstrate using C++/Java how the brute force method works along with its time complexity analysis:
worst case, average case and best case.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
}
System.out.println("Array elements to be sorted are :");
System.out.println("Please refer to the file");
System.setOut(o);
for(int i=0;i<n;i++)
{
System.out.println(a[i]+" ");
}
a[n]=99999;
start=System.nanoTime();
ssort(a,n);
end=System.nanoTime();
System.out.println("\nThe sorted elements are :");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.setOut(console);
long estimatedTime=end-start;
System.out.println("\nSelection Sort in Average case is:
"+(estimatedTime/1000000000.0)+"s");
System.out.println("******************************************");
start= System.nanoTime();
ssort(a,n);
end=System.nanoTime();
estimatedTime=end-start;
System.out.println("\nSelection Sort in best case is: "+
(estimatedTime/1000000000.0)+"s");
System.out.println("******************************************");
generateworstcase(a,n);
start= System.nanoTime();
ssort(a,n);
end=System.nanoTime();
estimatedTime=end-start;
System.out.println("\nSelection Sort in worst case is: "+
(estimatedTime/1000000000.0)+"s");
System.out.println("******************************************");
}
static void generateworstcase(int a[],int n)
{
for (int i = 0; i < n-1; i++)
{
int max_element = i;
for (int j = i+1; j < n; j++)
if (a[j] > a[max_element])
max_element = j;
if(max_element!=i)
{
int temp = a[max_element];//swap the elements
a[max_element] = a[i];
a[i] = temp;
}
}
}
static void ssort(int array[],int n)
{
for (int i = 0; i < n-1; i++)
{
int min_element = i;
for (int j = i+1; j < n; j++)
}
}
OUTPUT:
2. 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.
Demonstrate using C++/Java how the divide-and-conquer method works along with its time complexity
analysis: worst case, average case and best case
import java.util.Scanner;
import java.util.Random;
import java.io.*;
System.out.println("******************************************");
bestcasegen(a,0,n-1);
start=System.nanoTime();
qsort(a,0,n-1);
Dept. of CSE Sri Sairam College of Engineering, Anekal, Bengaluru
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY 21CS42
end=System.nanoTime();
estimatedTime=end-start;
System.out.println("\nQuickSort in BestCase is:
"+(estimatedTime/1000000000.0)+"s");
System.out.println("******************************************");
}
OUTPUT:
3 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 tosort. Plot a graph of the time
taken versus non graph sheet. The elements can be read from a file orcan be generated using the random
number generator. Demonstrate using C++/Java how the divide and- conquer method works along with
its time complexity analysis: worst case, average case and best case.
import java.io.*;
import java.util.Random;
import java.util.Scanner;
try{
calc();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
}
void calc() throws FileNotFoundException
{
PrintStream o = new PrintStream(new File("A.txt"));
PrintStream console=System.out;
System.out.println();
mergesort(a,0,n-1);
System.out.println("Array elements to be sorted are :");
System.out.println("Please refer to the file");
System.setOut(o);
for(int i=0;i<n;i++)
{
System.out.println(a[i]+" ");
}
long startTime=System.nanoTime();
mergesort(a,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("\nThe sorted elements are :");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.setOut(console);
long estimatedTime=stopTime-startTime;
System.out.println("\nMerge sort in average case is:
"+(estimatedTime/1000000000.0)+" s");
System.out.println("******************************************");
startTime=System.nanoTime();
mergesort(a,0,n-1);
stopTime=System.nanoTime();
estimatedTime=stopTime-startTime;
System.out.println("\nMerge sort in Best case is:
"+(estimatedTime/1000000000.0)+" s");
System.out.println("******************************************");
generateWorstCase(a,0,n-1);
startTime=System.nanoTime();
mergesort(a,0,n-1);
stopTime=System.nanoTime();
estimatedTime=stopTime-startTime;
System.out.println("\nMerge sort in Worst case is:
"+(estimatedTime/1000000000.0)+" s");
System.out.println("******************************************");
}
void generateWorstCase(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
int[] left = new int[m - l + 1];
int[] right = new int[r - m];
split(arr, left, right, l, m, r);
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
join(arr, left, right, l, m, r);
}
}
static void join(int arr[], int left[], int right[], int l, int m,
int r)
{
int i;
for (i = 0; i <= m - l; i++)
arr[i] = left[i];
for (int j = 0; j < r - m; j++)
arr[i + j] = right[j];
}
static void split(int arr[], int left[], int right[], int l, int m,
int r)
{
for (int i = 0; i <= m - l; i++)
left[i] = arr[i * 2];
while(i<=mid)
resarray[k++]=a[i++];
while(j<=high)
resarray[k++]=a[j++];
for(int m=low;m<=high;m++)
a[m]=resarray[m];
}
OUTPUT:
Enter the array size
5000
******************************************
4 Write & Execute C++/Java Program To solve Knapsack problem using Greedy method
import java.util.Scanner;
public class FractionalKnapSack
{
double weight[];
double profit[];
double ratio[];
double m;
double sum;
FractionalKnapSack()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of objects: ");
int n= scan.nextInt();
weight = new double[n];
profit = new double[n];
ratio = new double[n];
System.out.println("Enter the object's weights");
for (int i = 0; i<n; ++i)
weight[i] = scan.nextDouble();
System.out.println("Enter the object's profits");
for (int i = 0; i<n; ++i)
profit[i] = scan.nextDouble();
for (int i = 0; i<n; ++i)
ratio[i] = profit[i] / weight[i];
System.out.println("Enter the Capacity of the knapsack: ");
m = scan.nextDouble();
scan.close();
}
int getNext()
{
double highest = 0;
int index = -1;
for (int i = 0; i<profit.length; ++i)
{
if (ratio[i] >highest)
{
highest = ratio[i];
index = i;
}
}
return index;
}
void fill()
{
System.out.print("Objects considered: ");
while(m>0)
{
int item = getNext();
if (item == -1) break;
System.out.print((item+1)+" ");
if(weight[item]<= m)
{
m=m-weight[item];
sum=sum+profit[item];
ratio[item]=0;
}
else
{
sum=sum+(profit[item]*(m/weight[item]));
m=0;
break;
}
}
System.out.println("\nThe Optimal Solution i.e.Maximum Profit =" + sum );
}
public static void main(String[] args)
{
FractionalKnapSack fk = new FractionalKnapSack();
fk.fill();
}
}
OUTPUT:
5 Write & Execute C++/Java Program To find shortest paths to other vertices from a given vertex in a
weighted connected graph, using Dijkstra's algorithm.
import java.util.Scanner;
public class Dijkstra
{
int graph[][]=new int[10][10];
int d[]=new int[10];
int p[]=new int[10];
int s[]=new int[10];
int n;
int source;
int min;
Dijkstra()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of vertices");
n=scan.nextInt();
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
graph[i][j]=scan.nextInt();
}
}
System.out.println("Enter the source vertex");
source=scan.nextInt();
}
void initialize()
{
for(int i=0;i<n;i++)
{
d[i]=graph[source][i];
p[i]=source;
}
s[source]=1;
}
void dijkstra()
{
relax(source);
for(int i=0;i<n;i++)
{
if(d[i]==99)
System.out.println(i+ "is not reachable from" +
source);
if(i!=source)
print_path(source,i);
}
}
OUTPUT:
5 2 5 0 4
99 99 6 4 0
1<--0=3
2<--1<--0=7
3<--1<--0=5
4<--3<--1<--0=9
6. Write & Execute C++/Java Program To find Minimum Cost Spanning Tree of a given connected undirected
graph using Kruskal's algorithm. Use Union-Find algorithms in your program.
import java.util.Scanner;
public class Kruskal
{
int cost[][]=new int[10][10];
int s[]=new int[10];
int t[][]=new int[10][10];
int n,sum,k,u,v,count;
Kruskal()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of vertices");
n=scan.nextInt();
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cost[i][j]=scan.nextInt();
for(int i=0;i<n;i++)
{
s[i]=i;
}
}
int findParent(int v)
{
while(s[v]!=v)
{
v=s[v];
}
return v;
}
void kruskal()
{
int i,j;
while(count<n-1)
{
int min=99;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(min>cost[i][j])
{
min=cost[i][j];
u=i;
v=j;
}
}
}
k++;
}
void printTree()
{
if(count==n-1)
{
System.out.println("Cost of Spanning tree is: "+sum);
System.out.println("The spanning tree is:");
for(k=0;k<n-1;k++)
{
System.out.println(t[k][0]+ " - "+t[k][1]);
}
System.exit(0);
}
}
}
}
OUTPUT:
7 Write & Execute C++/Java Program To find Minimum Cost Spanning Tree of a given connected undirected
graph using Prim's algorithm.
import java.util.Scanner;
public class Prims
{
int n;
int graph[][]=new int[10][10];
int p[]=new int[10];
int d[]=new int[10];
int s[]=new int[10];
int t[][]=new int[10][2];
int sum,k,source,u,v;
void createGraph()
{
Scanner scan =new Scanner(System.in);
System.out.println("Enter the number of vertices");
n=scan.nextInt();
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
graph[i][j]=scan.nextInt();
}
System.out.println("Enter an arbitrary vertex");
source=scan.nextInt();
scan.close();
}
void initialize()
{
for(int i=0;i<n;i++)
{
d[i]=graph[source][i];
p[i]=source;
}
s[source]=1;
}
void MST()
{
for(int i=1;i<n;i++)
{
int min=99;
for(int j=0;j<n;j++)
{
if(s[j]==0)
{
if(d[j]<=min)
{
min=d[j];
u=j;
}
}
}
t[k][0]=u;
t[k][1]=p[u];
k++;
for(v=0;v<n;v++)
{
if(s[v]==0 && graph[u][v]<d[v])
{
d[v]=graph[u][v];
p[v]=u;
}
}
}
}
void print()
{
if(sum>=99)
System.out.println("Spanning tree does not exist");
else
{
for(int i=0;i<n-1;i++)
{
System.out.println(t[i][0]+"->"+t[i][1]);
}
System.out.println("The cost of spanning tree is: "+sum);
}
}
OUTPUT:
8 Write C++/ Java programs to Solve All-Pairs Shortest Paths problem using Floyd's algorithm.
import java.util.Scanner;
public class Floyds
{
int cost[][];
int n;
Floyds()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of vertices");
n=scan.nextInt();
cost=new int[n+1][n+1];
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cost[i][j]=scan.nextInt();
}
}
}
void floyds()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cost[i][j]=Math.min(cost[i][j],
cost[i][k]+cost[k][j]);
printAllPairShortestPath();
}
void printAllPairShortestPath()
{
System.out.println("The shortest path matrix is");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
System.out.print(cost[i][j]+" ");
}
System.out.println();
}
}
OUTPUT:
Enter the number of vertices
4
Enter the cost matrix
9 Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic programming
import java.util.*;
public class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=999;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n = s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to
"+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return min;
}
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int
temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return minindex;
}
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}
OUTPUT:
10. Write C++/ Java programs to Solve 0/1 Knapsack problem using Dynamic Programming method.
import java.util.Scanner;
public class Knapsack
{
static int max(int a,int b)
{
return (a>b)?a:b;
}
for(int i=1;i<=n;i++)
profit[i]=scan.nextInt();
System.out.println("Enter the capacity");
int m=scan.nextInt();
knapsack(wt,profit,m,n);
}
}
OUTPUT:
Enter the number of objects 4
Enter the weight
2 1 3 2
Enter the profit
12 10 20 15
Enter the capacity
5
The optimal solution is: 37
The objects selected are:
1
2
4
11. Design and implement C++/Java 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. For example, if S = {1, 2, 5, 6, 8} and d= 9, there are
two solutions {1, 2, 6} and {1, 8}. Display a suitable message, if the given problem instance doesn't have a
solution.
import java.util.Scanner;
void getData()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
int n = sc.nextInt();
w = new int[n + 1];
x = new int[n + 1];
System.out.println("Enter " + n + " Elements :");
for (int i = 1; i <= n ; i++)
{
w[i] = sc.nextInt();
total += w[i];
}
System.out.println("Enter the sum to be obtained: ");
sum = sc.nextInt();
if (total < sum)
{
System.out.println("No possible subsets!!!");
System.exit(1);
}
sc.close();
}
void subset(int s, int k, int r)
{
x[k] = 1;
if (s + w[k] == sum)
{
System.out.print("{");
for (int i = 1; i <= k; i++)
{
if(x[i]==1)
System.out.print(" " + w[i]);
}
System.out.println(" }");
}
else if ((s + w[k] + w[k + 1]) <= sum)
{
subset(s + w[k], k + 1, r - w[k]);
}
if ((s + r - w[k]) >= sum && (s + w[k + 1]) <= sum)
{
x[k] = 0;
subset(s, k + 1, r - w[k]);
}
}
public static void main(String[] args)
{
OUTPUT:
12. Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected undirected Graph G
of n vertices using backtracking principle.
import java.util.Scanner;
Hamiltonian()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=scan.nextInt();
x=new int[n+1];
x[1]=1;
for(int i=2;i<=n;i++)
x[i]=0;
adj=new int[n+1][n+1];
System.out.println("Enter the adjacency matrix");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
adj[i][j]=scan.nextInt();
}
}
}
while(true)
{
x[k]=(x[k]+1)%(n+1);
if(x[k]==0) return;
if(adj[x[k-1]][x[k]] ==1)
{
for(j=1;j<k;j++)
if(x[j]==x[k]) break;
if(j==k)
{
if((k<n)|| (k==n &&adj[x[n]][1]==1))
return;
}
}
}
}
void H(int k)
{
OUTPUT: