DAA Lab Manual Simplified Version
DAA Lab Manual Simplified Version
----------------------------------------------------------------------------------------------------------------------------------------------------
1
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
2
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
4 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.
5 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 divideand-conquer method works along with its time complexity analysis: worst
case, average case and best case.
6 Implement in Java, the 0/1 Knapsack problem using
(a) Dynamic Programming method.
(b)Greedymethod.
7 From a given vertex in a weighted connected graph, find shortest paths to other vertices
usingDijkstra's algorithm. Write the program in Java.
8 Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
9 Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
10 Write Java programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) ImplementTravellingSalesPerson problemusingDynamicprogramming.
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.
----------------------------------------------------------------------------------------------------------------------------------------------------
3
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
1a.
Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii)
Branch (iv) Phone Write a Java program to create nStudent objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
importjava.util.Scanner;
voidreadStudentDetails(inti)
{
System.out.println("Enter Usn Name Branch Phone No. of student "+(i+1));
Scanner s = new Scanner(System.in);
usn = s.nextInt();
name = s.next();
branch = s.next();
phone = s.nextInt();
}
voiddisplayStudentDetails()
{
System.out.println("usn+”\t”+name+”\t”+branch+”\t”+phone);
}
public static void main(String[] args)
{
System.out.println("Enter number of students : ");
Scanner s1 = new Scanner(System.in);
int n = s1.nextInt();
Student stud[] = new Student[n];
for(inti = 0 ; i<num ; i++)
{
stud[i] = new Student();
stud[i].readStudentDetails(i);
}
System.out.println("---------------------------------------------------------------------");
System.out.format"USN\tName\tBranch\tPhone_No");
System.out.println("---------------------------------------------------------------------");
for(inti = 0 ; i< n ; i++)
{
stud[i].displayStudentDetails();
----------------------------------------------------------------------------------------------------------------------------------------------------
4
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}
}
Output :
1b.
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to
demonstrate its working.
importjava.util.Scanner;
import static java.iang.asystem.exit;
publicclass Stack {
ints[] = new int[5];
int top;
Stack(){
top=-1;
}
voidpush()
{
if(top==s.length-1)
{
System.out.println("Stack Overflow");
return;
}
----------------------------------------------------------------------------------------------------------------------------------------------------
5
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
else
{
System.out.println("Enter element to be pushed");
Scanner scan=newScanner(System.in);
int item=scan.nextInt();
s[++top]=item;
System.out.println("Item pushed: "+s[top]);
}
}
void pop()
{
if(top==-1)
{
System.out.println("Stack underflow");
return;
}
else
{
intele=s[top--];
System.out.println("popped element is "+ele);
}
}
void display()
{
if(top == -1)
System.out.println("Stack is empty");
for(inti=top ;i>=0;i--)
{
System.out.println(s[i]);
}
}
publicstaticvoid main(String args[])
{
Stack sc=newStack();
intch;
do
{
System.out.println("1:push\t2:pop\t3:display\t4:exit\t\n Enter your choice");
Scanner s = new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1: sc.push();
break;
case 2: sc.pop();
break;
case 3:System.out.println(“the stack elements are”);
sc.display();
break;
case 4:exit(0);
default: System.out.println(“enter choice from 1 to 4”);
}
}while(ch>0);
----------------------------------------------------------------------------------------------------------------------------------------------------
6
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}
Output
2a.
Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing
three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a
Java program to read and display at least 3 staff objects of all three categories.
importjava.util.Scanner;
classStaffmain {
int StaffId,Phone,Salary;
String name;
----------------------------------------------------------------------------------------------------------------------------------------------------
7
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Scanner scan = newScanner(System.in);
Void read_staff_details()
{
StaffId=scan.nextInt();
name=scan.next();
Phone=scan.nextInt();
Salary=scan.nextInt();
}
}
voidread_domain_publication()
{
Super.read_staff_details();
domain=scan.next();
no_publication=scan.nextInt();
}
voiddisplay_domain_publictaion()
{
System.out.print(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+domain+"\t"+no_publication);
System.out.println("\n");
}
}
public class Technical extends Staffmain{
String skills;
voidread_skills()
{
Super .read_staff_details();
skills=scan.next();
}
voiddisplay_skills()
{
System.out.print(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+skills);
System.out.println("\n");
}
}
publicclass Contract extendsStaffmain{
int period;
voidread_contract_period()
{
Super .read_staff_details();
period=scan.nextInt();
}
voiddisplay_contract_period()
{
System.out.println(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+period);
----------------------------------------------------------------------------------------------------------------------------------------------------
8
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("\n");
}
}
publicclass Staff {
publicstaticvoid main(String[] args)
{
int n1, n2, n3;
Scanner scan= newScanner(System.in);
System.out.println("How many number of Teaching Staff details do you wish to enter\n");
int n1=scan.nextInt();
Teachingteach[]=new Teaching[n1];
System.out.println("How many number of Technical Staff details do you wish to enter\n");
int n2=scan.nextInt();
Technicaltech[]=new Technical[n2];
System.out.println("How many number of contract Staff do you wish to enter");
int n3=scan.nextInt();
Contract cont[]=new Contract[n3];
for(inti=0;i<n1;i++)
{
System.out.println("EnterSt_id\tName\tPh_no\tsalary\tdomain\tno_publictaion of
teaching staff "+(i+1));
teach[i]=new Teaching();
teach[i].read_domain_publication();
}
for(inti=0;i<n2;i++) {
System.out.println("Enter St_id\tName\tPh_no\tsalary\tskills of technical staff"+
(i+1));
tech[i]=new Technical();
tech[i].read_skills();
}
for(inti=0;i<n3;i++)
{
System.out.println("Enter St_id\tName\tPh_no\tsalary\tContract period of contract
staff” +(i+1));
cont[i]=new Contract();
cont[i].read_contract_period();
}
if(n1>0){
System.out.println("Teaching staff details are \n");
System.out.println("--------------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tdomain\tno_publictaion");
System.out.println("--------------------------------------------------------");
for(inti=0;i<n1;i++)
{
teach[i].display_domain_publictaion();
}
else
{
System.out.println("no teaching staff details found");
}
if(n2>0){
----------------------------------------------------------------------------------------------------------------------------------------------------
9
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("--------------------------------------------------");
System.out.println("Technical staff details are \n");
System.out.println("--------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tskills\n");
System.out.println("--------------------------------------------------");
for(inti=0;i<n2;i++)
{
tech[i].display_skills();
}
else
{
System.out.println("no technical staff details found \n");
}
if(n3>0)
{
System.out.println("--------------------------------------------------");
System.out.println("Contract staff details are \n");
System.out.println("--------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tContract period");
System.out.println("---------------------------------------------------");
for(inti=0;i<n3;i++)
{
cont[i].display_contract_period();
}
{
System.out.println("no contract staff details found \n");
}
}
}
Output
How many number of Teaching Staff details do you wish to enter
1
How many number of Technical Staff details do you wish to enter
1
How many number of contract Staff do you wish to enter
1
Enter St_id Name Ph_no salary domain no_publictaion of teaching staff 1
Reena
123
34567
1321
CSE
2
Enter St_id Name Ph_no salary skills of technical staff 1
Seena
67
2342
3242
C
Enter St_id Name Ph_no salary Contract period of contract staff 1
1
----------------------------------------------------------------------------------------------------------------------------------------------------
10
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
34543
213
3242
2
Teaching staff details are
--------------------------------------------------------
Name St_id Ph_no salary domain no_publictaion
--------------------------------------------------------
Reena 123 34567 1321 CSE 2
--------------------------------------------------------
Technical staff details are
--------------------------------------------------------
Name St_id Ph_no salary skills
--------------------------------------------------------
Seena 67 2342 3242 C
--------------------------------------------------------
Contract staff details are
--------------------------------------------------------
Name St_id Ph_no salary Contract period
--------------------------------------------------------
1 34543 213 3242 2
--------------------------------------------------------
2b.
Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format should
be dd/mm/yyyy. Write methods to read customer data as and display as using StringTokenizer class
considering the delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer; public class ReadNameDate {
public static void main(String args[]){
ReadNameDate readNameDate = new ReadNameDate(); String customerData=
readNameDate.readCustomeNameDob();
readNameDate.displayCustomerNameDob(customerData);
}
private String readCustomeNameDob() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name and DOB in <name,dd/mm/yyyy> format");
String str = scanner.next();
if(!str.startsWith("<") ||!str.endsWith(">"))
{ System.out.println("Please enter it in proper format");
}
return str; }
private void displayCustomerNameDob(String customerData)
{ String st = customerData.substring(0, customerData.length());
StringTokenizer stringTokenizer = new StringTokenizer(st, "<,/>"); String finalString =null;
while(stringTokenizer.hasMoreTokens
()){ if(finalString == null){
finalString = stringTokenizer.nextToken();
}else{
}
}
finalString =finalString+","+stringTokenizer.nextToken();
System.out.println("<"+finalString+">");
----------------------------------------------------------------------------------------------------------------------------------------------------
11
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}
SAMPLE INPUT AND OUTPUT:
Enter name and DOB in <name,dd/mm/yyyy> format <surya,11/12/2000>
<surya,11,12,2000>
3a.
Write a Java program to read two integers a andb. Compute a/b and print, when b is not zero. Raise an
exception when b is equal to zero.
importjava.util.Scanner;
publicclass Division
{
publicstaticvoid main(String[] args)
{
int a, b, res;
Scanner scan = newScanner(System.in);
System.out.print("Enter the values of a& b");
a = scan.nextInt();
b = scan.nextInt();
try
{
res = a/b;
System.out.println("Result = "+res);
}
catch (ArithmeticException e)
{
System.out.println("Can't divide by zero" + e);
return;
}
}
}
Output:
Enter the values of a& b
50
Can't divide by zero
Enter the values of a& b
56 2
Res = 28
----------------------------------------------------------------------------------------------------------------------------------------------------
12
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
3b.
Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number andprints;
third thread will print the value of cube of the number.
importjava.lang.Thread;
importjava.util.*;
}
Class CubeThread extends Thread
{
int x3;
public CubeThread(intn)
{
x3 = n;
}
Public void run()
{
System.out.println("Cube of a Number"+x3+"is="+(x3*x3*x3));
}
}
Class RandomThread extends Thread
{
publicvoid run()
{
try
{
----------------------------------------------------------------------------------------------------------------------------------------------------
13
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
While(true)
{
Random r = new Random();
int n = r.nextInt(100);
sleep(1000);
System.out.println("The random number is” + n);
SquareThread t2 = newSquareThread(n);
t2.start();
CubeThread t3 = new CubeThread(n);
t3.start();
}
}
catch (InterruptException e)
{
System.out.println("”EXception!!”);
}
}
}
Output:
The random number is 49
Square of a number 49 is 2401
Cubeof a number 49 is 117649
4.
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.
importjava.util.*;
classQuickSort
{
int[] x = new int[100];
int[] temp = new int[100];
int n;
voidreadElementsRandomly()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of elements : ");
----------------------------------------------------------------------------------------------------------------------------------------------------
14
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
n = scan.nextInt();
Random r = newRandom();
for(inti = 0 ; i<n ; i++)
x[i] = r.nextInt(100);
System.out.println("Elements are");
printSortedArray();
}
Output.
Enter the number of elements :
7
Elements are
4 55 23 546 12 43 12
Sorted elements
4 12 12 23 43 55 546
5.
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 divideand-conquer method works along with its time complexity
analysis: worst case, average case and best case.
importjava.util.*;
publicclassMergeSort
{
public static void merge(int A[], intl,intm, int h)
{
int[] b = new int[100];
inti=l,j=m+1, k=l;
while (i<= m && j < h)
{
if (A[i] <= A[j])
B[k++] = A[i++];
else
B[k++] = A[j++];
}
/* Copy remaining elements of B[] if any */
while (i<= m)
B[k++] = A[i++];
/* Copy remaining elements of C[] if any */
----------------------------------------------------------------------------------------------------------------------------------------------------
16
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
while (j <= h)
[k++] = A[j++];
for(k=l ; k<=h ; k++)
A[k] = b[k];
}
public static voidmergesort(int A[], intl,int h)
{
if(l<=h) return;
int m = (l+h)/2;
mergeSort(a, l, m);
mergeSort(a, m+1, h);
merge(a, l, m, h);
}
Publicstaticvoidmain(String[] args)
{
Scanner s = new Scanner(System.in);
Random r = new Random();
inti, n;
int a[] = new int[20];
long start, end;
System.out.println("Enter number of elements : ");
n = scan.nextInt();
System.out.println("Enter” +n+ “integer nos");
for(i=0 ; i<n ; i++)
a[i]=r.nextInt();
System.out.println(“Entered elements are”);
for(i=0 ; i<n ; i++)
System.out.println(a[i]);
start = System.nanoTime();
mergesort(a,0,n-1);
end = System.nanoTime();
System.out.println("Sorted elements are”);
for(i=0 ; i<n ; i++)
System.out.println(a[i]);
double tm = end – start;
System.out.println("Total time taken =" +tm/1000000000+" ms");
}
}
Output.
Enter the number of elements :
7
Elements are
4 55 23 546 12 43 12
Sorted elements
4 12 12 23 43 55 546
Enter number of elements : 10000
Total time taken =7 ms
Enter number of elements : 32432
Total time taken =11 ms
Enter number of elements : 32465
----------------------------------------------------------------------------------------------------------------------------------------------------
17
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Total time taken =10 ms
Enter number of elements : 324345
Total time taken =65 ms
6a.
Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method.
importjava.util.*;
publicclassKnapsackDynamic
{
int max(inta,int b)
{
return (a>b)?a:b;
}
publicstaticvoid main(String args[])
{
int m, n, i, j, profit = 0;
intw[] = newint[100], p[] = newint[100], x[] = newint[100], v[] = newint[10][10];
Scanner scan = newScanner(System.in);
System.out.println("Enter the number of objects");
n = scan.nextInt();
System.out.println("Enter the maximum capacity of knapsack");
m = scan.nextInt();
for(i = 1 ; i<= n ; i++)
{
System.out.println("Enter the weights&profits of "+i+ “ objects”);
w[i] = scan.nextInt();
p[i] = scan.nextInt();
}
for(i = 0 ; i<= n ; i++)
{
for(j = 0 ; j <= m; j++)
{
if(i ==0 || j == 0)
v[i][j] = 0;
elseif(w[i] >= j)
v[i][j] = v[i-1][j];
else
v[i][j] = max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
profit=v[i][j];
}
}
System.out.print(“Result profit table is:”);
for(i = 0 ; i<= n ; i++)
{
for(j = 0 ; j <= m; j++)
{
System.out.print(v[i][j]+"\t");
}
System.out.print(“ “);
}
for(i = 0 ; i<= n ; i++)
----------------------------------------------------------------------------------------------------------------------------------------------------
18
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
x[i]=0;
i = n, j = m;
while(i != 0 && j != 0)
{
if(v[i][j] != v[i-1][j])
{
X[i]=1; j = j - w[i];
}
i = i - 1;
}
System.out.println("Objects selected are”);
for(i = 0 ; i<= n ; i++)
{
if(x[i]==1)
System.out.println("”\t”+i);
}
System.out.println("Optimal Solution = “ +profit);
}
}
Output.
Enter the number of objects: 2
Enter the maximum capacity of knapsack: 4
Enter the weights& profits of 1 object: 1 15
Enter the weights& profits of 2 object: 2 20
Result profit table is
0 0 0 0 0
0 15 15 15 15
0 15 20 35 35
6b.
Implement in Java, the Knapsack problem using Greedy method.
importjava.util.Scanner;
public class KnapsackGreedy
{
Public static void main(String args[])
{
double n, m, rc=0, temp, profit=0;
inti, j;
double w[] = newdouble[10], p[] = newdouble[10], pw[] = newdouble[10], x[] =
newdouble[100];
Scanner scan = newScanner(System.in);
System.out.println("Enter the number of objects");
n = scan.nextInt();
System.out.println("Enter the maximum capacity of knapsack");
m = scan.nextInt();
for(i = 1 ; i<= n ; i++)
{
System.out.println("Enter the weights&profits of "+i+ “ objects”);
w[i] = scan.nextInt();
----------------------------------------------------------------------------------------------------------------------------------------------------
19
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
p[i] = scan.nextInt();
pw[i]=p[i]/w[i];
}
// code for sorting
for(inti = 0 ; i< n - 1 ; i++ )
{
for(int j = 0 ; j < n - i -1 ; j++)
{
if(pw[j] <pw[j+1])
{
temp = pw[j];
pw[j] = pw[j+1];
pw[j+1] = temp;
temp = w[j];
w[j] = w[j+1];
w[j+1] = temp;
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
System.out.println("PW array”);
System.out.println("\tProfit\tWeight\tPW");
for(inti = 0 ; i< n ; i++)
{
System.out.println("\t"+p[i]+"\t"+w[i]+"\t"+pw[i]);
}
for(i = 0 ; i<n ; i++)
x[i]=0;
rc=m;
for(i = 0 ; i<n &&rc> 0 ; i++)
{
if(w[i] >rc)
x[i]= rc/w[j];
else
x[i] = 1;
profit += x[i] * p[i];
System.out.println(“profit is”+ profit+"\t"+ x[i]+"\t"+ +p[j]);
rc =rc - w[j];
}
System.out.println("Maximum profit = "+profit);
}
Output.
Enter the number of objects: 2
Enter the maximum capacity of knapsack: 5
Enter the weights& profits of 1 object: 1 2
Enter the weights& profits of 2 object: 3 4
PW array
Profit Weight PW
----------------------------------------------------------------------------------------------------------------------------------------------------
20
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
2.0 1.0 2.0
4.0 3.0 1.333
Profit is: 2.0 1.0 2.0
Profit is: 6.0 1.0 4.0
Maximum profit = 6.0
7.
From a given vertex in a weighted connected graph, find shortest paths to other vertices usingDijkstra's
algorithm. Write the program in Java.
importjava.util.*;
publicclassDijktras
{
publicstaticvoiddijkstra_soln(int n, intsrc, int cost[][])
{
int min, i, j, u;
int d = newint[100] ;
int v = newint[100];
8.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal'salgorithm. Use
Union-Find algorithms in your program.
importjava.util.*;
publicclassKruskal
{
publicint p[] = new int[10];
publicint cost[][] = new int[10][10];
publicint find(int v)
{
while (p[v] != 0)
v = p[v];
return v;
}
publicvoid union(int u,int v)
{
if(i<j)
p[j] = i;
else
p[i] = j;
}
voidkruskal_soln(int n)
{
inti,j, min, u, v, a=0,b=0, ne=0, mincost=0;
while(ne <n)
----------------------------------------------------------------------------------------------------------------------------------------------------
22
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
{
for(i = 1, min=999 ; i<= n ; i++)
{
for( j = 1 ; j <= n ; j++)
{
if(cost[i][j] < min)
{
a = i;
b = j;
min = cost[i][j];
}
}
}
if(min != I)
{
u = find(a);
v = find(b);
cost[a][b] =cost[b][a] = 999;
if(u != v)
{
System.out.println(ne++ +"edge("+a +" to" +b +") "+min);
mincost += min;
union(u,v);
}
}
}
System.out.println("Mincost="+mincost);
}
----------------------------------------------------------------------------------------------------------------------------------------------------
23
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Output.
Enter the number of vertices in the Graph : 4
Enter the weight matrix (enter 999 if no edge exists)
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0
Kruskals solution
1 edge(1 to 2) 1
2 edge(1 to 4)2
3 edge(3 to 4)3
Mincost = 6
9.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm.
importjava.util.*;
Output.
Enter the number of vertices in the Graph : 4
Enter the weight matrix (enter 999 if no edge exists)
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0
Prims solution
1 edge(1 to 2) 1
2 edge(1 to 4)2
3 edge(3 to 4)3
Mincost = 6
10a.
Write Java programs toImplement All-Pairs Shortest Paths problem using Floyd's algorithm.
importjava.util.Scanner;
publicclass Floyds
{
public static int main(int a, int b)
{
return((a<b)?a:b);
}
public static voidfloyds_soln(int a[][], int n)
{
inti,j,k;
for(k = 0 ; k < n ; k++)
for(i = 0 ; i<n ; i++)
for(j = 0 ; j <n; j++)
a[i][j] =min(a[i][j], a[i][k]+a[k][j]);
}
Floyds solution
Shortest path length matrix
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
10b.
Write Java programs toImplement Travelling Sales Person problem using Dynamic programming.
importjava.util.*;
publicclass TSP
{
publicstaticvoid main(String args[])
{
int c[][] = new int[10][10], tour[] =new int[10];
Scanner scan = newScanner(System.in);
inti, j, n, cost;
System.out.print("TSP Dynamic Programming");
System.out.print("Enter the number of cities : ");
n = scan.nextInt();
if(n ==1)
{
----------------------------------------------------------------------------------------------------------------------------------------------------
26
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("Path is not possible");
System.exit(0);
}
System.out.println("Enter the cost matrix (enter 999 if no edge exists)");
edge = newint[vc][vc];
for(i = 1 ; i< n ; i++)
for( j =1 ; j <n ; j++)
c[i][j] = scan.nextInt();
for(i = 1 ; i< n ; i++)
tour[i] = i;
cost=tspdp(c, tour, 1, n);
System.out.println("Accurat path is");
for(i = 1 ; i< n ; i++)
System.out.println(tour[i]+ "");
System.out.println("1");
System.out.println("Accurate Mincost = " +cost);
}
if(start == n - 1)
return c[tour[n-1]][tour[n]] + c[tour[n]][1];
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.
Import java.util.Scanner;
Public class SumofSubset {
publicstaticvoid main(Stringargs[])
{
SumofSubset s = newSumofSubset();
inti, n, sum=0;
12.
Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n
vertices using backtracking principle.
importjava.util.Scanner;
Output.
Enter the number of vertices in a graph : 5
Total no. of edges: 8
Enter edges: 1 2
----------------------------------------------------------------------------------------------------------------------------------------------------
30
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Enter edges: 1 3
Enter edges: 1 6
Enter edges: 2 3
Enter edges: 2 6
Enter edges: 3 4
Enter edges: 4 5
Enter edges: 5 6
Hamiltonian cycle
1234561
1265431
1345621
1654321
----------------------------------------------------------------------------------------------------------------------------------------------------
31