DAA Labmanual 2022-23 4sem
DAA Labmanual 2022-23 4sem
DAA Labmanual 2022-23 4sem
R N S Institute of Technology
RR Nagar Post, Bengaluru – 560 098.
Laboratory Manual
Academic Year March 2023 – June 2023
Semester IV
Smitha B A
Course Plan
Assistant Professor, Department of AI & ML
Author
RNS Institute of Technology, Bengaluru.
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
21CS42.1 3
21CS42.2 3
21CS42.3 3
21CS42.4 3
Week - 2
Week - 3
Week - 4
17/04/ -22/04 Changing Wallpaper - Mobile App 18
Week 5
Week 6
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
SYLLABUS
Modu
Program
le No
A. 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
1 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.
A. 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.
2 B. 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.
A. Design and implement C++/Java Program to find a subset of a given set S = {Sl,
5 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.
B. Design and implement C++/Java Program to find all Hamiltonian Cycles in a
connected undirected Graph G of n vertices using backtracking principle.
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
2 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.
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
3 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.
Write & Execute C++/Java Program to solve Knapsack problem using Greedy method.
4
Write & Execute C++/Java Program to find shortest paths to other vertices from a given
5 vertex in a weighted connected graph, using Dijkstra's algorithm
Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
6 connected undirected graph using Kruskal's algorithm. Use Union-Find algorithms in your
program.
Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
7
connected undirected graph using Prim's algorithm.
Write C++/ Java programs to Solve All-Pairs Shortest Paths problem using Floyd's
8 algorithm.
Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic
9 programming.
Write C++/ Java programs to Solve 0/1 Knapsack problem using Dynamic Programming
10 method.
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 =
11 {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.
Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected
12 undirected Graph G of n vertices using backtracking principle.
Scheme of Evaluation
Assessment Details (both CIE and SEE)
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). A student shall
be deemed to have satisfied the academic requirements and earned the credits allotted to each
subject/ course if the student secures not less than 35% (18 Marks out of 50) in the semester-end
examination (SEE), and a minimum of 40% (40 marks out of 100) in the sum total of the CIE
(Continuous Internal Evaluation) and SEE (Semester End Examination) taken together Continuous
Internal Evaluation:
Practical Sessions need to be assessed by appropriate rubrics and viva-voce method. This will
contribute to 20 marks.
• Rubrics for each Experiment taken average for all Lab components – 15 Marks.
The sum of three tests, two assignments, and practical sessions will be out of 100 marks and will
be scaled down to 50 marks
CO 5: Apply and analyze backtracking, branch and bound methods and to describe P, NP and
NPComplete problems
System.out.println(“Namaste! Welcome”);
}
}
OUTPUT :
Namaste! Welcome
Example 2
JAVA program to print Name, College and Place.
Name : Raghu
College : RNSIT
Place : Bengaluru
Example 3
JAVA program to accept emp_name, emp_id, emp_salary and print them.
import java.util.Scanner;
public class Example3 {
public static void main(String[] args)
{ int mp_id;
String emp_name;
double emp_salary;
Scanner read = new Scanner(System.in);
System.out.println("Enter the employee name");
emp_name=read.nextLine();
}
}
OUTPUT :
Kushal
Enter the employee ID
46
Enter the employee salary
87000.50
Example 4
JAVA program to perform mathematical operations on an expression.
import java.util.Scanner;
public class Example4 {
public static void main (String[] args)
{ double a,b,res=0;
char c;
Scanner read = new Scanner(System.in);
System.out.println("Enter the expression");
a=read.nextDouble();
c=read.next().charAt(0);
b=read.nextDouble();
switch(c)
case '+' :
res=a+b;
break;
case '-' :
res=a-b;
break;
case '*' :
res=a*b;
break;
case '/' :
if(b==0)
{
System.out.println("Divide by zero error");
System.exit(0);
else
res=a/b;
break;
default :
System.out.println("Invalid Entry");
System.exit(0);
}
System.out.println("Result is : "+res);
}
OUTPUT :
4 - 12
Result is : -8.0
4.5 / 3
Result is : 1.5
5/0
Example 5
JAVA program to read and print array elements.
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) { int []a = new int[10];
Scanner read = new Scanner(System.in);
System.out.println("Enter the array elements");
for(int i=0;i<a.length;i++)
a[i]=read.nextInt();
System.out.println("Entered array elements : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
}
}
OUTPUT :
Example 6
JAVA program to print array elements.
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
}
}
OUTPUT :
Entered array elements are
1 2 3 4 5
Example 7
JAVA program to read n array elements and print the sum of array elements.
import java.util.Scanner;
public class Example7 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n,sum=0;
n=read.nextInt();
for(int i=0;i<a.length;i++)
sum+=a[i];
4
Enter the array elements
2 6 7 22
Sum of array elements is 37
Example 8
JAVA program to read and print 2 x 2 matrix.
import java.util.Scanner;
public class Example8 {
for(int j=0;j<2;j++)
a[i][j]=read.nextInt();
for(int j=0;j<2;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
OUTPUT :
Enter the matrix
34 -12
44 90 Entered
matrix is
34 -12
44 90
Example 9
JAVA program to read and print M x N matrix.
import java.util.Scanner;
public class Example9 {
public static void main(String[] args) {
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
OUTPUT :
Enter the number of rows
3
Enter the number of columns
3
Enter the matrix
12 56 4
7 13 -3
77 14 6
12 56 4
7 13 -3
77 14 6
Example 10
JAVA program to print 2 x 2 matrix.
System.out.println();
}
}
}
OUTPUT :
Entered matrix is
1 2
3 4
Example 11
JAVA program to find the biggest element in the given M x N matrix.
import java.util.Scanner;
Example 12
JAVA program to print volume using an object.
class Box1
{
double width,height,depth;
}
public class Example12
{
public static void main(String[] args)
{
Box1 b1=new Box1();
b1.height=10;
b1.width=20;
b1.depth=30;
}
}
OUTPUT :
Volume is 6000.0
LAB Programs
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.
ALGORITHM:
Program:
import java.util.Random;
Output:
Array size: 5000 | Time taken: 15ms
Array size: 10000 | Time taken: 63ms
Array size: 15000 | Time taken: 142ms
Array size: 20000 | Time taken: 256ms
Array size: 25000 | Time taken: 394ms
Array size: 30000 | Time taken: 565ms
Array size: 35000 | Time taken: 768ms
Array size: 40000 | Time taken: 1006ms
Array size: 45000 | Time taken: 1281ms
Array size: 50000 | Time taken: 1592ms
The above code first generates a random array of size 5000 using the Random class. It
then measures the time taken to sort arrays of various sizes ranging from 5000 to 50000 in
steps of 5000 using System.nanoTime(). The time taken is then printed to the console.
To analyze the time complexity, we can look at the number of comparisons and swaps
made by the algorithm. In the worst case, Selection Sort makes n-1 comparisons and n-1
swaps, giving it a time complexity of O(n^2). In the best case, if the array is already
sorted, it makes n-1 comparisons and 0 swaps, giving it a time complexity of O(n). In the
average case, it still makes n-1 comparisons and swaps, giving it a time complexity of
O(n^2).
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.
ALGORITHM:
ALGORITHM Quicksort(A[l...r]) //Sorts subarray by quicksort
//Input: A subarray A[l...r] of A[0...n-1], defined by its left and right indices l and r
Quicksort(A[l...s-1])
Quicksort(B[s+1...r])
ALGORITHM Partition(A[l...r])
//Partitions a subarray by using its first element as a pivot
//Input: A subarray A[l...r] of A[0...n-1], defined by its left and
right //indices l and r (l<r)
until i ≥ j
return j
import java.util.Random;
import java.util.Scanner;
{
/* function that consider last element as pivot,
place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
public static int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);
int n = a.length;
System.out.println("\nBefore sorting array elements are - ");
Main q1 = new Main();
q1.printArr(a, n);
q1.quick(a, 0, n - 1);
System.out.println("\nAfter sorting array elements are - ");
q1.printArr(a, n);
System.out.println();
}
*/
public static void main(String[] args)
{
int a[]= new int[100000];
//a[n]=9999;
start=System.currentTimeMillis();
quick(a,0,n-1);
end=System.currentTimeMillis();
Output1
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
5000
Array elements to be sorted are :
1045
6967
7672
3119
…..
The sorted elements are :
3
4
7
8
…..
The time taken to sort is 3133233ns
******** ******************* *******
Output 2:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
6000
Array elements to be sorted are:
948
1527
360
…
The sorted elements are:
2
5
8
11
12
13
13
14
..
The time taken to sort is 2647573ns
******** ******************* *******
OUPUT 3:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
1
2
3
4
…
20
The sorted elements are:
1
2
3
4
….
20
The time taken to sort is 28925ns
******** ******************* *******
OUTPUT 4
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
20
18
18
16
….
2
1
The sorted elements are:
1
2
3
4
…
18
20
The time taken to sort is 32657ns
******** ******************* *******
Output 5:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
4
6
7
9
2
13
16
18
19
7
11
15
9
10
16
23
34
12
4
7
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.
ALGORITHM :
ALGORITHM Mergesort(A[0...n-1])
Merge(B, C, A)
if B[i]≤ C[j]
k ← k+1
if i = p
copy C[j...q-1] to A[k...p+q-1]
else
import java.util.Scanner;
import java.util.Random;
class Main {
public static void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
/* temporary Arrays */
int LeftArray[] = new int[n1];
int RightArray[] = new int[n2];
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
start=System.currentTimeMillis();
mergeSort(a,0,n-1);
end=System.currentTimeMillis();
System.out.println("\nThe sorted elements are : ");
for(int i=0; i<n; i++)
System.out.println(a[i]+" ");
Output 2:
********** MERGE SORT PROGRAM *********
Enter the number of elements to be sorted
6000
Array elements to be sorted are :
2853
3407
8435
8882
3709
…
The sorted elements are :
0
0
1
1
1
….
The time taken to sort is 1256530873 ns
******** ********************** *******
4. Write & Execute C++/Java Program. To solve Knapsack problem using Greedy
method.
// ordered such that P[i]/w[i] ≥ P[i+1]/w[i+1]. m is the knapsack size and x[1:n] is
float u = m;
for (i = 1; i ≤ n; i++) {
u - = w[i];
}
}
Greedy method.
import java.util.Scanner;
class GreedyKnapsack
{
private int n;
private int m;
//private int[][] array;
private int [] w;
private int [] p;
m=max_qty;
OUTPUT
Enter no of items :
3
Enter the weights of each items :
18
15
10
Enter the profit of each items :
25
24
15
Enter the knapsack capacity :
Dept. of AI&ML, RNSIT Page 31 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
20
Quantity of item number: 2 added fully
Quantity of item number: 3 added is 0.5
The total profit is : 31.5
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.
ALGORITHM :
ALGORITHM Dijkstra(G)
for i ← 0 to |V| - 1 do
import java.util.*;
public class dijkstra
{
public static void main(String[] args)
{
int i, j;
dij(cost,dist,sv,n,path,visited);
printpath(sv,n,dist,path,visited );
if(cost[sv][i] == 999)
path[i] = 0;
else
path[i] = sv;
}
visited[sv]=1;
while(count<=n)
{
min = 999;
for(int w=1; w<=n; w++)
if((dist[w]< min) && (visited[w]==0))
{
min = dist[w];
v = w;
}
visited[v] = 1;
count++;
int t=path[w];
System.out.println("The path is:");
System.out.print(" "+w);
while(t != sv)
{
System.out.print("<-->"+t);
t=path[t];
}
System.out.print("<-->"+sv);
}
}
}
}
OUTPUT
**** DIJKSTRA'S ALGORITHM ******
Enter the number of nodes:
5
Enter the cost matrix
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
The entered cost matrix is
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
Enter the source vertex:
Dept. of AI&ML, RNSIT Page 34 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
1
The shortest distance between
1-> =2 is :3
The path is:
2<-->1The shortest distance between
1-> =3 is :7
The path is:
3<-->2<-->1The shortest distance between
1-> =4 is :5
The path is:
4<-->2<-->1The shortest distance between
1-> =5 is :9
The path is:
5<-->4<-->2<-->1
********* *************** *********
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.
ALGORITHM :
ALGORITHM Kruskal(G)
// Kruskal’s algorithm for constructing a minimum spanning tree
// Input: A weighted connected graph G = <V, E>
// Output: ET, the set of edges composing a minimum spanning tree of G
Sort E in non-decreasing order of the edge weights w(ei1) ≤ . . . ≤ w(ei|E|)
ET ← Ø; ecounter ← 0 //initialize the set of tree edges and its size k ← 0
while ecounter < |V| - 1 do
k ← k+1
if ET U {eik} is acyclic
ET ← ET U {eik}; ecounter ← ecounter + 1
return ET
import java.util.Scanner;
public class kruskalUnion
{
static int [] parent =new int [50];
static int [][]cost = new int [10][10];
static int a,b,i,j,u,v,n,min,noe=1,mincost=0;
System.out.println(noe-1 + "Edge("+a+","+b+")="+min);
mincost+=min;
parent[v]=u;
}
cost[a][b]=cost[b][a]=999;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=read.nextInt();
while(noe<n)
{
min=999;
for(i=1; 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);
union();
}
System.out.println("minimum cost ="+mincost);
}
}
OUTPUT:
3Edge(1,2)=3
4Edge(2,6)=4
5Edge(4,6)=5
minimum cost =15
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.*;
public class prims
{
public static void main(String[] args)
{
int cost[][]=new int[10][10];
int i, j, mincost = 0;
mincost=pr(cost,n,mincost);
nearV[1]=0;
for(i=1; i<n; i++)
{
int min=999;
for(j=1;j<=n;j++)
{
if(nearV[j]!=0 && cost[j][nearV[j]]<min)
{
min=cost[j][nearV[j]];
u=j;
}
}
t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;
nearV[u] = 0;
OUTPUT
********* PRIMS ALGORITHM *********
Enter the number of nodes
6
Enter the cost matrix
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 5 999 4
999 999 5 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
The entered cost matrix is
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 5 999 4
999 999 5 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
Minimum Spanning Tree Edges and costs are :
Dept. of AI&ML, RNSIT Page 38 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
8. Write C++/ Java programs to, Solve All-Pairs Shortest Paths problem using Floyd's
algorithm.
Floyd's algorithm.
ALGORITHM :
ALGORITHM Floyd( W[1...n, 1...n] )
// Implement Floyd’s algorithm for all-pairs shortest-paths problem
// Input: The weight matrix W of a graph with no negative-length cycle
// Output: The distance matrix of the shortest path’s lengths
D ← W //is not necessary if W can be overwritten for k
← 1 to n do
for i ← 1 to n do
for j ← 1 to n do
D[i, j] ← min{ D[i, j], D[i, k] + D[k, j] }
return D
import java.util.Scanner;
public class floyd
{
public static void main(String[] args)
{
int a[][]=new int[10][10];
int i, j;
for(i=1;i<=n;i++)
{
for(j=1; j<=n; j++)
{
System.out.print(a[i][j]+"\t");
Dept. of AI&ML, RNSIT Page 39 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
}
System.out.println();
}
floydalgo(a,n);
OUTPUT:
***********FLOYD'SALGORITHM**********
Enter the number of vertices:
4
Enter the adjacency matrix
0 999 3 999
2 0 999 999
0701
6 999 999 0
Entered adjacency matrix is:
0 999 3 999
2 0 999 999
0 7 0 1
6 999 999 0
All pair shortest path matrix:
0 10 3 4
2 0 5 6
Dept. of AI&ML, RNSIT Page 40 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
0 7 0 1
6 16 9 0
************ ********* **************
9. Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic
programming.
import java.util.*;
import java.util.Scanner;
int i, j,cost;
System.out.println("**** TSP DYNAMIC PROGRAMMING *******");
if(n==1)
{
System.out.println("Path is not possible");
System.exit(0);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
for(i=1;i<=n;i++)
tour[i]=i;
for(i=1;i<=n;i++)
System.out.print(tour[i]+"->");
System.out.println("1");
temp[start+1] = tour[i];
temp[i] = tour[start+1];
if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)
{
mincost = c[tour[start]][tour[i]] + ccost;
return mincost;
}
}
10. Write C++/ Java program to, to solve Knapsack problem using Dynamic
Programming method
ALGORITHM :
ALGORITHM MFKnapsack(i, j)
// Implements the memory function method for the knapsack problem
// Input: A nonnegative integer i indicating the number of the first items being
// V[0..n, 0..W] whose entries are //initialized with -1’s except for row 0 and column 0
if V[i, j] < 0
if j < Weights[i]
value ← MFKnapsack(i – 1, j)
else
value ← max(MFKnapsack(i – 1, j), Values[i] +
MFKnapsack(i – 1, j-Weights[i]))
V[i, j] ← value
return V[i, j]
import java.util.Scanner;
public class knap
{
public static void main(String[] args)
{
int v[][]=new int[30][30], w[]=new int[10], p[]=new int[10];
Scanner in = new Scanner(System.in);
int i, j;
displayinfo(m,n,w,p);
knapsack(m,n,w,p,v);
System.out.println("ITEM\tWEIGHT\tPROFIT");
for(int i=1; i<=n; i++)
System.out.println(i+"\t"+w[i]+"\t"+p[i]);
System.out.println("Capacity = "+m);
}
if(item == 0)
System.out.println("NIL\t Sorry ! No item can be placed in Knapsack");
System.out.println("\n***************************************");
}
}
OUTPUT
************* KNAPSACK PROBLEM ***********
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.
ALGORITHM :
void SumOfSub (float s, int k, float r)
// Find all subsets of w[1:n] that sum to m. The values of x[j], 1<=j<k, have already
x[k] =1;
if (s+w[k] == m)
x[k] = 0;
import java.util.Scanner;
public class subset
{
static int c=0;
public static void main(String[] args)
{
int w[]=new int[10];
for(i=0;i<n;i++)
sum=sum+w[i];
System.out.println("SUM ="+sum);
finalsubset(0,0,sum,x,w,d);
if(c==0)
System.out.println("Subset is not possible ! ");
if(cs+w[k] == d)
{
c++;
System.out.print("\nSolution "+c+" is {");
for(int i=0;i<=k;i++)
if(x[i] == 1)
{
System.out.print(w[i]+" ");
}
System.out.print("}");
}
else if((cs + w[k] + w[k+1]) <= d)
finalsubset(cs + w[k], k+1, r-w[k],x,w,d);
OUTPUT
********** SUBSET PROBLEM ************
Enter the number of elements:
5
Enter the elements in increasing order
12568
Enter the value of d:
9
SUM =22
Solution 1 is {1 2 6 }
Solution 2 is {1 8 }
********** ********* *************
12. Design and implement C++/Java Program to find all Hamiltonian Cycles in a
connected undirected Graph G of n vertices using backtracking principle.
ALGORITHM :
void Hamiltonian (int k)
if (!x[k]) return;
if (k == n) {
} while (1);
void NextValue(int k)
// x[1],..., x[k-1] is a path of k-1 distinct vertices. If x[k]==0, then no vertex has as yet
// been assigned to x[k]. After execution x[k] is assigned to the next highest
// numbered vertex which i) does not already appear in x[1], x[2],..., x[k-1]; and
package javaapplication11;
import java.util.Scanner;
public class P12new {
static int [] x = new int [25];
static void Next_Vertex(int G[][],int n,int k){
int j;
while(true)
{
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
return;
if(G[x[k-1]][x[k]]!=0)
{
for(j=1;j<=k-1;j++)
{
if(x[j]==x[k])
break;
}
if(j==k)
{
if((k<n)||((k==n)&&(G[x[n]][x[1]]!=0)))
return;
}
}
}
}
{
System.out.println("\n");
for(i=1;i<=n;i++)
System.out.print(x[i] +"-->");
System.out.println(x[1]);
}
else
H_Cycle(G,n,k+1);
}
}
public static void main(String[] args) {
int i,j,n;
int [][] G = new int [25][25];
Scanner read = new Scanner(System.in);
System.out.println("Enter the number of vertices of the graph");
n=read.nextInt();
System.out.println("Enter the Path adjacency matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
G[i][j]=read.nextInt();
x[i]=0;
}
}
x[1]=1;
System.out.println(" \n Hamiltonian Cycles are");
H_Cycle(G,n,2);
}
}
OUTPUT1:
Enter the number of vertices of the graph
8
Enter the Path adjacency matrix
01100010
10100001
11010000
00101000
00010100
00001010
10000101
01000010
1-->3-->4-->5-->6-->7-->8-->2-->1
OUTPUT2:
Enter the number of vertices of the graph
6
Enter the Path adjacency matrix
011100
101010
110110
101011
011101
000110
1-->2-->5-->6-->4-->3-->1
1-->3-->2-->5-->6-->4-->1
1-->3-->4-->6-->5-->2-->1
1-->4-->6-->5-->2-->3-->1
1-->4-->6-->5-->3-->2-->1
2. State the Euclid’s algorithm for finding GCD of two given numbers.
ALGORITHM Euclid (m, n)
// Computes gcd(m,n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n
return m.
4. What are important problem types? (or) Enumerate some important types of
problems.
1.Sorting 2. Searching 3. Numerical problems
4. Geometric problem 5. Combinatorial Problems 6. Graph problems
7. String processing problems
16. What do you mean by time complexity and space complexity of an algorithm?
Time complexity indicates how fast the algorithm runs. Space complexity deals with extra memory it
require. Time efficiency is analyzed by determining the number of repetitions of the basic operation
as a function of input size. Basic operation: the operation that contributes most towards the running
time of the algorithm The running time of an algorithm is the function defined by the number of steps
(or amount of memory) required to solve input instances of size n.
18. What are the different criteria used to improve the effectiveness of algorithm?
(i) The effectiveness of algorithm is improved, when the design, satisfies the following constraints to
be minimum. Time efficiency - how fast an algorithm in question runs. Space efficiency – an extra
space the algorithm requires
(ii) The algorithm has to provide result for all valid inputs.
for(j=N/2;j>0;j--)
sum++;
Time Complexity= (N * N) / 2= N2 /2
Є O (N2)
Checking the no.of times basic operation executed depends on size of input. If it depends
on some additional property, then best, worst, avg. cases need to be investigated
Set up sum expressing the no. of times the basic operation is executed. (establishing
order of growth)
The time taken by an algorithm grows with the size of the input. So the running time of the program
depends on the size of its input. The input size is measured as the number of items in the input that is
a parameter n is indicating the algorithm’s input size.
{ S : = 0.0
For i=1 to n do S : - S
Dept. of AI&ML, RNSIT Page 57 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
+ a[i]; Return S; }
if(n≤0) then
Return 0.0;
The central assumption of the RAM model is that instructions are executed one after another, one
operation at a time. Accordingly, algorithms designed to be executed on such machines are called
Sequential algorithms.
The central assumption of the RAM model does not hold for some newer computers that can execute
operations concurrently, i.e., in parallel algorithms that take advantage of this capability are called
Parallel algorithms.
45.Define Flowchart.
A method of expressing an algorithm by a collection of connected geometric shapes containing
descriptions of the algorithm’s steps.
To prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
Example: Correctness of Euclid’s algorithm for computing the greatest common divisor stems from
correctness of the equality gcd (m, n) = gcd (n, m mod n).
The ²Worst case-Efficiency” of an algorithm is its efficiency for the worst-case input of size n, which
is an input (or inputs) of size n for which the algorithm runs the longest among all possible inputs of
that size.
Ex: if you want to sort a list of numbers in ascending order when the numbers are given in descending
order. In this running time will be the longest.
The ²Best case-Efficiency” of an algorithm is its efficiency for the Best-case input of size n, which is
an input(or inputs) of size n for which the algorithm runs the fastest among all possible inputs of that
size.
Ex: if you want to sort a list of numbers in ascending order when the numbers are given in ascending
order. In this running time will be the smallest.
The “Amortized efficiency” applies not only a single run of an algorithm but rather to a sequence of
operations performed on the same data structure. It turns out that in some situations a single operation
can be expensive ,but the total time for an entire sequence of n such operations is always significantly
better than the worst case efficiency of that single operation multiplied by n. This is known as
“Amortized efficiency
It is logical to investigate the algorithm’s efficiency as a function of some parameter n indicating the
algorithm’s input size.
Example: It will be the size of the list for problems of sorting, searching, finding the list’s smallest
element, and most other problems dealing with lists.
Let Cop be the time of execution of an algorithm’s basic iteration on a particular computer
and let C (n) be the number of times this operation needs to be executed for this algorithm.
Then we can estimate the running time T(n) of a program implementing this algorithm on
1/2n(n-1)=(1/2)n2-1/2n £ 1/2 n2 for all n³0.(we have proved upper inequality) now 1/2n(n-1)=(1/2)n2 -
1/2n³(1/2)n2-1/2n*1/2n(for all n³2)=1/4 n2 hence we can select c2=1/4,c1=1/2 and n0=2.
The notations O, W and Q and are used to indicate and compare the asymptotic orders of growth of
functions expressing algorithm efficiencies
MODULE 2
DIVIDE AND CONQUER
Unsuccessful searches
Dept. of AI&ML, RNSIT Page 61 2021-22
21CS42: Design and Analysis of Algorithms Laboratory
Θ (logn)
11. what is Merge sort? and Is insertion sort better than the merge sort?
Merge sort is divide and conquer strategy that works by dividing an input array in to two halves,sorting
them recursively and then merging the two sorted halves to get the original array sorted Insertion sort
works exceedingly fast on arrays of less then 16 elements, though for large‘n’ its computing time is
O(n2).
Time efficiency T(n)of many divide and conquer algorithms satisfies the equation
T(n)=a.T(n/b)+f(n).This is the general recurrence relation.
17. What can we say about the average case efficiency of binary search?
A sophisticated analysis shows that the average number of key comparisons made by binary search is
only slightly smaller than that in the worst case Cavg(n) log2n
POSTORDER - The root is visited after visiting the left and right subtrees(in that order)
24.Explain Merge sort algorithm with an example by constructing recursive call tree.justify
how it uses divide and conquer method.
25.Explain Quick sort algorithm with an example by constructing recursive call tree.justify
how it uses divide and conquer method.
29.Expalin with an example how stragens’s matrix multiplication uses divide and conquer
approach. Write its time complexity.
30.list the problems that can be solved using divide and conquer method.
33.Explain Topoloical sort using both OFS and source removal method with an example.
justify how it uses decrease and conquer approach.
35.List the problems that can be solved using decrease and conquer method.
MODULE 3
GREEDY METHOD
Locally optimal(best local choice among all feasible choices available on that step)
13. Write the difference between the Greedy method and Dynamic programming.
Finding a permutation for the n programs so that when they are stored on the tape in this order the
MRT is minimized.This problem fits the ordering paradigm.
26.List the different problems that can be solved using greedy method.
30.What are different types of knapsack problems,explain with an example.justify how the knapsack
problem uses greedy method.
31.Expain job requencing with deadlines with an example.justify how it uses greedy method.
34.Explain prims algorithm with an example .justify how it uses greedy method.write its complexity.
35.Explain Kruskal’s algorithm with an example .justify how it uses greedy method.write its
complexity.
36.what are the proceduaral difference between prims and kruskal’s algorithm.
37.Explain single source shortest path problem using dijkstras algorithm with an example.justify how
it uses greedy method.
38.How single source shortest path problem can be converted in to all pairs shortest path
problem.justify with an example.
44.Once the max/min heap constructed show how the inserution or deletion will taker place.
45.Explain the Heap sort with an example .justify how it uses transform and conquer approach.
MODULE 4
DYNAMIC PROGRAMMING
1. Write the difference between the Greedy method and Dynamic programming.
Dynammic pgmg. Used. If probabilities of searching for elements of a set are known then finding
optimal BST for which the average number of comparisons in a search is smallest possible.
.
15. Explain Warshalls algorithm
Warshall's algorithm constructs the transitive closure of a given digraph with n vertices through a series
of n by n Boolean matrices R(0), ………, R(k-l)R(k),…….., R(n)
Each of these matrices provides certain information about directed paths in the digraph.
fashion but only once, just necessary sub problems of a given problem and recording their solutions in
a table.
22.List the problems which can be solved using dynamic programming method.
27.Explain warshall’s algorithm with an example.Justify how it uses dynamic programming method.
28.Explain Floud’s Algorithm with an example.Justify how it uses dynamic programming method.
31.What is optimal binary search tree? How it can be differentiate with binary search tree justify with
an example.
33.suggest different methods which can be solved knaprack problem using dynamic programming?
35.Explain travelling salesperson problem with an example.justify how it user dynamic programming
method.
MODULE 5
BACKTRACKING
1.what are the requirements that are needed for performing Backtracking?
To solve any problem using backtracking, it requires that all the solutions satisfy a complex set of
constraints. They are: i. Explicit constraints. ii. Implicit constraints.
i
2.Define state space tree.
The tree organization of the solution space is referred to as state space tree.
8. Define a E – node.
E – node (or) node being expanded. Any live node whose children are currently being generated is
called as a E – node.
11.What are the searching techniques that are commonly used in Branch-and-Bound method
The searching techniques that are commonly used in Branch-and-Bound method. I FIFO ii.
LIFO iii. LC iv. Heuristic search
Let g = (V, E) be a directed. The tour of G is a directed simple cycle that includes every vertex in V.
The cost of a tour is the sum of the cost of the edges on the tour. The traveling salesperson problem is
to find a tour of minimum cost.In branch and bound technique of TSP problem Lower bound lb= s/2
24. Give the time complexity and space complexity of traveling salesperson problem.
constructed solution that may still lead to lead to a complete solution; otherwise it is called
nonpromising.
34.Mention two reasons to terminate a search path at the current node in a state-space tree of a
branch and bound algorithm.
The value of the node's bound is not better than the value of the best solution seen so far. The node
represents no feasible solutions because the constraints of the problem are already violated.
Find the most valuable subset of n items of given positive integer weights and values that fit into a
knapsack of a given positive integer capacity.
47.Define Traversals.
When the search necessarilyinvolves the examination of every vertex in the object being searched
it is called a traversal.