Professional Documents
Culture Documents
(UPDATED) DAA_LAB_MANUAL 2023
(UPDATED) DAA_LAB_MANUAL 2023
NAME : .......................................................................................................................................................................................................................................................................................................................................................................................................................................
USN :.....................................................................................................................................................................................................................................................................................................................................................................................................................................................
Mission
To impart high quality education in Engineering, Technology and Management with a
Difference, Enabling Students to Excel in their Career by
1. Attracting quality Students and preparing them with a strong foundation in fundamentals so as to
achieve distinctions in various walks of life leading to outstanding contributions
2. Imparting value based, need based, choice based and skill based professional education to the
aspiring youth and carving them into disciplined, World class Professionals with social
responsibility
3. Promoting excellence in Teaching, Research and Consultancy that galvanizes academic
consciousness among Faculty and Students
4. Exposing Students to emerging frontiers of knowledge in various domains and make them suitable
for Industry, Entrepreneurship, Higher studies, and Research & Development
5. Providing freedom of action and choice for all the Stake holders with better visibility
Mission
The Department of Computer Science and Engineering (Data Science) will make every effort
to promote an intellectual and an ethical environment in which the strengths and skills of
Computer Professionals will flourish by
1. Provide quality undergraduate education in both theoretical and applied computer science to
solve real world problems
2. Conduct research to develop algorithms that solve complex problems involving multi-
dimensional high volume data through intelligent inferencing.
3. Develop good linkages with industry and research organizations within India and abroad to
expose students to global problems and find optimal solutions.
4. Creating confident Graduates who can contribute to the nation through high levels
of commitment following ethical practices and with integrity
PREFACE
We have developed this comprehensive laboratory manual on Design & Analysis of Algorithms
Laboratory (21CS42) with the primary objectives: To make the students comfortable with Java
Programming Language using the eclipse software.
This material is comprised of solutions for 12 lab experiments, additional programs to show the
different ways to solve the same problem and encourage students to come up with their own creative
ways to solve them and to gain better knowledge on real world problems and includes Viva questions.
Our profound and sincere efforts will be fruitful only when students acquire the extensive knowledge
by reading this manual and apply the concepts learnt apart from the requirements specified in Design
& Analysis of Algorithms Laboratory as prescribed by VTU, Belagavi.
Department of CSE(DS)
ACKNOWLEDGMENT
A material of this scope would not have been possible without the contribution of many people. We express
our sincere gratitude to Dr. Satish R Shetty, Chairman, RNS Group of Companies for his magnanimous
support in all our endeavors.
We are grateful to Dr. Ramesh Babu H S, Principal, RNSIT and Dr. Srinivas A, HOD, CSE(DS) for extending
their constant encouragement and support.
Our heartfelt thanks to Dr. Sreevidya R C for unparalleled contribution throughout the preparation of this
comprehensive manual. We also acknowledge our colleagues for their timely suggestions and unconditional
support.
Department of CSE(DS)
Sl.
Parameters Excellent Good Needs Improvement
No.
a. Design, Program follows syntax and Program has few logical Syntax and semantics
implementation,and semantics of Java programming errors, moderately of Java programming is
demonstration language. Demonstrates the demonstrates all possible not clear (1)
(5 marks) complete knowledge of the concepts implemented in
program written (5) programs (3)
b. Result and All expected results are Moderately debugs the Expected results are not
documentation demonstrated successful, all program and Partial demonstrated properly,
(5 marks) errors are debugged with own documentation. unable to debug the
practical knowledge and clear (3) errors and no proper
documentation according to the documentation (1)
guidelines (5)
TEST-1
TEST-2 5𝟎 5
Write
Date of Exen. Viva Total Teacher
Program # Lab programs up
Execution (10) (10) 30 Signature
(10)
10
11
12
Avg.
Total 30 𝟑𝟎 5
Marks
C: RECORD (10) 2𝟎
TABLE OF CONTENTS
SL. PAGE
NO. CONTENTS
NO.
LABORATORY PROGRAMS
PART A
1 Selection Sort
1.1 Program
1.2 Output
2 Quick Sort
2.1 Program
2.2 Output
3 Merge Sort
3.1 Program
3.2 Output
4 Greedy Kanpsack
4.1 Program
4.2 Output
10 Dynamic Knapsack
10.1 Program
10.2 Output
11 Sum of Subset
11.1 Program
11.2 Output
viii
Design & Analysis of Algorithms Laboratory (21CS42)
12 Hamilton Cycle
12.1 Program
12.2 Output
ix
Design & Analysis of Algorithms Laboratory (21CS42)
SYALLABUS
SEMESTER – IV
DESIGN & ANALYSIS OF ALGORITHMS LABORATORY
(Effective from the academic year 2021-2022)
1. Explain the methods of analyzing the algorithms and to analyze performance of algorithms.
State algorithm’s efficiencies using asymptotic notations.
3. Solve problems using algorithm design methods such as the brute force method, greedy
method, divide and conquer, decrease, and conquer, transform, and conquer, dynamic
programming, backtracking and branch and bound.
4. Choose the appropriate data structure and algorithm design method for a specified
application.
5. Introduce P and NP classes.
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 non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and-conquer 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 non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using 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 non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and-conquer method works along with its time complexity analysis: worst
case, average case, and best case.
5. From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm. Write the program in Java.
x
Design & Analysis of Algorithms Laboratory (21CS42)
6. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.
7. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
8. Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method.
9. Write Java programs to implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
10. Write Java programs to implement Travelling Salesperson problem using Dynamic
programming.
11. Design and implement in Java 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.
12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
• Rubrics for each Experiment taken average for all Lab programs – 15 Marks.
• Viva-Voce– 5 Marks (more emphasized on demonstration topics)
xi
Design & Analysis of Algorithms Laboratory (21CS42)
SELECTION SORT
1. Sort a given set of n integer elements using ALGORITHMS selection s o r t method and
compute its timecomplexity. 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 on graph sheet. The elements can
be read from a fileor can be generated using the random number generator. Demonstrate
using Java how thedivide-and-conquer method works along with its time complexity
analysis: worst case, averagecase and best case.
package first_demo;
import java.util.Random;
import java.util.Scanner;
sc.nextInt();
a = new int[max];
Random generator = new
Page | 12
Design & Analysis of Algorithms Laboratory (21CS42)
Random();
for (i = 0; i < n; i++)
a[i] =
generator.nextInt(200);
System.out.println("Array
before sorting");
for (i = 0; i < n; i++)
System.out.println(a[i]
+ " ");
long startTime =
System.nanoTime();
selectionSort(a,n);
long stopTime =
System.nanoTime();
System.out.println(a[i]);
}
Page | 13
Design & Analysis of Algorithms Laboratory (21CS42)
QUICK SORT
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 on graph sheet. The elements can be read from a
fileor can be generated using the random number generator. Demonstrate using Java how
thedivide-and-conquer method works along with its time complexity analysis: worst case,
averagecase and best case.
Quick sort is important sorting algorithm that is based on the divide-and conquers approach.
Quick sort divides them according to their value. Specifically, it rearranges elements of a given
array A[O .. n - 1] to achieve its partition, a situation where all the elements before some position
s are smaller than or equal to A[s] and all the elements after positions are greater than or equal
to A[s]:
Program
import java.util.Random;
import java.util.Scanner;
class QuickSort {
static int comparisons = 0;static int[] arr;
static void quickSort(int low, int high) {if (low < high) {
comparisons += 1;
i = i + 1;
}
Page | 14
Design & Analysis of Algorithms Laboratory (21CS42)
j = j - 1;
}
if (i < j) {
comparisons += 1;
interchange(i, j);
}
}
arr[low] = arr[j];arr[j] =
pivot; return j;
}
arr[i] = i + 1;
}
break;
}
Page | 15
Design & Analysis of Algorithms Laboratory (21CS42)
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 16
Design & Analysis of Algorithms Laboratory (21CS42)
MERGE SORT
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 on graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and-conquer method works along with its time complexity analysis: worst
case, average case and best case.
Merge sort is a perfect example of a successful application of the divide-and conquer technique.
It sorts a given array A[O .. n - 1] by dividing it into two halves A[0 .. [n/2] -1] and A[n/2 .. n -
1], sorting each of them recursively, and then merging the two smaller sorted arrays into a single
sorted one.
Program
class MergeSort {
static int comparisons = 0;static int[] arr;
static void mergeSort(int low, int high) {if (low < high) {
comparisons += 1;
static void merge(int low, int mid, int high) {int n = high - low + 1;
int[] t_arr = new int[n];
int i = low, j = mid + 1, k = 0;
Page | 17
Design & Analysis of Algorithms Laboratory (21CS42)
Page | 18
Design & Analysis of Algorithms Laboratory (21CS42)
// }
Page | 19
Design & Analysis of Algorithms Laboratory (21CS42)
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 20
Design & Analysis of Algorithms Laboratory (21CS42)
KNAPSACK PROBLEM
4. Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method.
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.
Program
import java.util.Scanner;class
Knapsack {
private int[] weight, profit;private int
capacity, n;
Knapsack() {
Scanner scanner = new Scanner(System.in);
Page | 21
Design & Analysis of Algorithms Laboratory (21CS42)
void fill() {
int[][] K = new int[n + 1][capacity + 1];
capacity;
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 22
Design & Analysis of Algorithms Laboratory (21CS42)
Page | 23
Design & Analysis of Algorithms Laboratory (21CS42)
Program
import java.util.Scanner;class
Knapsack {
Knapsack() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of Items");int n =
scanner.nextInt();
weight = new double[n]; profit = new
double[n]; ratio = new double[n];
solnVector = new double[n];
int getNext() {
int index = -1;
double highest = 0;
Page | 24
Design & Analysis of Algorithms Laboratory (21CS42)
void fill() {
double currentWeight = 0;double
currentProfit = 0;
}
}
Page | 25
Design & Analysis of Algorithms Laboratory (21CS42)
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 26
Design & Analysis of Algorithms Laboratory (21CS42)
DIJKSTRA'S ALGORITHM
7. From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm. Write the program in Java.
Program
i++) {
if ((src - 1) == i) {continue;
}
System.out.println("Shortest Distance from"+src+"to
"+(i+1)+"is"+dist[i]);
}
}
Page | 27
Design & Analysis of Algorithms Laboratory (21CS42)
visited[src - 1] = true;
visited[unvis] = true;
return dist;
}
}
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 28
Design & Analysis of Algorithms Laboratory (21CS42)
KRUSKAL'S ALGORITHM
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.
Program
class Edge {
int src; int dest;
int weight;
class Main {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in);
System.out.println("Enter number of Vertices");int n =
scanner.nextInt();
int k = 0;
for (int i = 0; i < n; i++) {
Page | 29
Design & Analysis of Algorithms Laboratory (21CS42)
sort(edges);
System.out.println();
System.out.println("Minimum Cost of Spanning Tree: "
+ minCost);
}
Page | 30
Design & Analysis of Algorithms Laboratory (21CS42)
edges[j + 1] = temp;
}
}
}
}
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 31
Design & Analysis of Algorithms Laboratory (21CS42)
PRIM’S ALGORITHM
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
Program
visited[srcVertex - 1] = true;
Page | 32
Design & Analysis of Algorithms Laboratory (21CS42)
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 33
Design & Analysis of Algorithms Laboratory (21CS42)
FLOYD'S ALGORITHM
10. a. Write Java programs to implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
Program
Page | 34
Design & Analysis of Algorithms Laboratory (21CS42)
}
}
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 35
Design & Analysis of Algorithms Laboratory (21CS42)
10. b. Write Java programs to implement Travelling Salesperson problem using Dynamic
programming.
Program
import java.util.ArrayList;import
java.util.Scanner;
class Main {
static int[][] graph;static int n,
src;
Page | 36
Design & Analysis of Algorithms Laboratory (21CS42)
Page | 37
Design & Analysis of Algorithms Laboratory (21CS42)
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 38
Design & Analysis of Algorithms Laboratory (21CS42)
SUBSET
11. Design and implement in Java 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.
Program
Page | 39
Design & Analysis of Algorithms Laboratory (21CS42)
} else {
boolean[] tempSolution = solution.clone();
tempSolution[index] = false;
subSet(total, index - 1, tempSolution);
tempSolution[index] = true; subSet(total - arr[index],
index - 1,
tempSolution);
}
}
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 40
Design & Analysis of Algorithms Laboratory (21CS42)
BACKTRACKING
12 Design and implement in Java to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
Program
import java.util.Scanner;class
Hamiltonian {
static int[][] graph; static int[] soln;
static int n, count = 0;
// Instatiate Solution array(1 Indexed), (Default Value is 0)soln = new int[n + 1];
if (count == 0) {
System.out.println("No Hamiltonian Cycle");
Page | 41
Design & Analysis of Algorithms Laboratory (21CS42)
}
}
static void hamiltonian(int k) {while (true) {
nextValue(k);
Test Cases
Test No Input Parameters Expected Output Obtained Output
Page | 43
Design & Analysis of Algorithms Laboratory (21CS42)
Appendix-A
This section lists the Viva questions for each lab session:
SELECTION SORT
1. As the input size increases, the performance of selection sort decreases. (T/F)
2. What is the best case, worst case, average case time complexity for quick sort
algorithm?
3. Explain working of selection sort
QUICK SORT
MERGE SORT
1. What is the best case, worst case, average case time complexity for merge sort
algorithm?
2. What is the output of merge sort after the 1st pass given the following sequence of
numbers?
25 57 48 37 12 92 86 33
3. What is the running time of merge sort?
4. What technique is used to sort elements in merge sort?
5. Is merge sort in place sorting algorithm?
6. Define stable sort algorithm. Is merge sort stable?
WARSHALL’S ALGORITHM
Page | 44
Design & Analysis of Algorithms Laboratory (21CS42)
GRAPH TRAVERSALS
1. Define Back-Tracking.
2. Explain Sum of subset problem.
3. What is the time complexity of sum of subset problem?
4. Let S= {1,2,3,4,5} and d= 6. Obtain the subsets whose sum leads to d
Page | 45
Design & Analysis of algorithms (21CS42)
BACKTRACKING
Page 46