DAA Manual-Indira Final Cse 1 Compressed 1
DAA Manual-Indira Final Cse 1 Compressed 1
(18CSL47)
COURSE OUTCOME:
After the completion of this course the students will be able to:
CO1: Design algorithms using appropriate design techniques (brute-force, greedy, dynamic
programming, etc.)
CO2: Implement a variety of algorithms such assorting, graph related, combinatorial, etc., in
a high level language.
CO3: Analyze and compare the performance of algorithms using language features
CO4: Apply and implement learned algorithm design techniques and data structures to solve
real world problems.
1. A. 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 N
Student objects and print the USN, Name, Branch, and Phone of these objects with
suitable headings.
B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(),
and Display() methods to demonstrate its working.
2. A. Design a super class called Staff with details as Staff Id, 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.
B. 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
“/”.
3. A. Write a Java program to read two integers a and b. Compute a/b and print, when
b is not zero. Raise an exception when b is equal to zero.
B. 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 and prints; third thread will print the value of
cube of the number.
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 divide and-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) Greedy method.
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.
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal's algorithm. 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.
Note: All laboratory experiments (Twelve problems) are to be included for practical
examination. Students are allowed to pick one experiment from the lot. To generate
the data set use random number generator function. Strictly follow the instructions
as printed on the cover page of answer script for breakup of marks Marks
distribution: Procedure + Conduction + Viva: 20 + 50 + 10 (80). Change of experiment
is allowed only once and marks allotted to the procedure
Design and Analysis of Algorithms Laboratory [18CSL47]
1 a. 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 n Student objects and
print the USN, Name, Branch, and Phone of these objects with suitable headings.
Import java.util.Scanner;
class Student
{
String usn, name,branch,phone;
void read()
{
Scanner sobj=newScanner(System.in);
System.out.println("Enter Student USN");
usn=sobj.next();
System.out.println("Enter Student Name:");
name=sobj.next();
System.out.println("Enter Student branch:");
branch=sobj.next();
System.out.println("Enter Student phone no:");
phone=sobj.next();
}
void display()
{
System.out.println(usn+"..."+name+"..." +branch+"..."+phone);
}
}
publicclass Pgm1a {
publicstaticvoid main(String[] args)
{
int n;
Scanner sobj=newScanner(System.in);
System.out.println("Enter the Number of Students");
n=sobj.nextInt();
//array of objects
Student[] st=new Student[n];
System.out.println("Please enter the student details");
//creation of n objects
for(int i=0;i<st.length;i++)
{
st[i]=new Student();
}
//read student data
for(int i=0;i<st.length;i++)
{
st[i].read();
}
OUTPUT
Enter the Number of Students
2
Please enter the student details
Enter Student USN
is01
Enter Student Name:
abhi
Enter Student branch:
ise
Enter Student phone no:
9876543210
Enter Student USN
is02
Enter Student Name:
manu
Enter Student branch:
ise
Enter Student phone no:
9098765432
USN | Name || USN | Name
is01...abhi...ise...9876543210
is02...manu...ise...9098765432
1 b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
Import java.util.Scanner;
class Stack
{
finalint size=5;
intarr[] = newint[size];
int top = -1;
publicvoid push(int item)
{
if(top < size-1)
{
top++;
arr[top]=item;
System.out.println("The " + item + "is pushed into the stack");
}
else
{
System.out.println("Error !Stack Overflow ");
}
}
publicvoid pop()
{
if(top==-1)
{
System.out.println("error stack underflow");
}
else
{
intitem;
item =arr[top];
System.out.println("The " + arr[top] + " is poped out of the stack");
top--;
}
}
publicvoid display()
{
if(top==-1)
{
System.out.println("Stack Empty ");
}
else
{
System.out.println("Elements in stack ");
for(int i=0;i<=top;i++)
{
System.out.println(arr[i]);
}
}
}
}
publicclassStack_Demo
{
publicstaticvoid main(String[] args)
{
Stack s= newStack();
int x;
Scanner sobj=newScanner(System.in);
intch;
System.out.println("press 1 to push element");
System.out.println("press 2 to pop element");
System.out.println("press 3 to display elements");
System.out.println("press 4 to exit ");
do
{
}
}
OUTPUT
2 a. Design a super class called Staff with details as Staff Id, 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.
Import java.util.Scanner;
class Staff
{
intstaffid,salary;
String name, phone;
Staff(intstaffid, intsalary,Stringname,String phone )
{
this.staffid=staffid;
this.salary=salary;
this.name=name;
this.phone=phone;
}
void display()
{
System.out.println("Staff ID:"+staffid);
System.out.println("Salary:"+salary);
System.out.println("Name:"+name);
System.out.println("Phone:"+phone);
}
}
class Teaching extends Staff
{
String domain, publication;
Teaching(intstaffid,intsalary,Stringname,Stringphone,Stringdom,String pub)
{
super(staffid,salary,name,phone);
domain=dom;
publication=pub;
}
voiddisplayTeach()
{
System.out.println("Domain:"+domain);
System.out.println("Publication:"+publication);
System.out.println("-----------------------------");
}
}
class Technical extends Staff
{
String skills;
Technical(intstaffid,intsalary,Stringname,Stringphone,String skill)
{
super(staffid,salary,name,phone);
skills=skill;
}
voiddisplayTechnical()
{
System.out.println("Skils:"+skills);
System.out.println("-----------------------------");
}
}
class Contract extends Staff
{
int period;
Contract(intstaffid,intsalary,Stringname,Stringphone,int per)
{
super(staffid,salary,name,phone);
period=per;
}
publicvoiddisplayCont()
{
System.out.println("Period:"+period);
System.out.println("-----------------------------");
}
}
publicclass Pgm2a
{
publicstaticvoid main(String[] args)
{
intch, sid,salary,period;
String name,phone,domain,publication,skill;
System.out.println("Enter your category:1. Teaching, 2.Technical.3.Contract");
Scanner sobj=newScanner(System.in);
ch=sobj.nextInt();
switch(ch)
{
case 1: Teaching[] te=new Teaching[3];
for(int i=0;i<te.length;i++)
{
System.out.println("Enter SID,Salary,Name,Phone,domain and
Publications");
sid=sobj.nextInt();
salary=sobj.nextInt();
name=sobj.next();
phone=sobj.next();
domain=sobj.next();
publication=sobj.next();
te[i]=new Teaching(sid,salary,phone,name,domain,publication);
}
for(int i=0;i<te.length;i++)
{
te[i].display();
te[i].displayTeach();
}
break;
case 2: Technical[] tech=new Technical[3];
for(int i=0;i<tech.length;i++)
{
System.out.println("Enter SID,Salary,Name,Phone and Skills");
sid=sobj.nextInt();
salary=sobj.nextInt();
name=sobj.next();
phone=sobj.next();
skill=sobj.next();
tech[i]=new
Technical(sid,salary,phone,name,skill);
}
for(int i=0;i<tech.length;i++)
{
tech[i].display();
tech[i].displayTechnical();
}
break;
case 3: Contract[] con=new Contract[3];
for(int i=0;i<con.length;i++)
{
System.out.println("Enter SID,Salary,Name,Phone and period");
sid=sobj.nextInt();
salary=sobj.nextInt();
name=sobj.next();
phone=sobj.next();
period=sobj.nextInt();
con[i]=new Contract(sid,salary,phone,name,period);
}
for(int i=0;i<con.length;i++)
{
con[i].display();
con[i].displayCont();
}
break;
default: System.out.println("Invalid option");
}
}
}
OUTPUT 1:
-----------------------------
Staff ID:3
Salary:12000
Name:7898767899
Phone:suma
Domain:programming
Publication:iccstar
-----------------------------
OUTPUT 2:
Name:9098767876
Phone:raghava
Period:4
OUTPUT 3:
2 b. 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;
class Customer
{
String cname,dob;
Scanner sobj=new Scanner(System.in);
void read()
{
System.out.println("Enter Customer name:");
cname=sobj.next();
System.out.println("Enter Customer DOB in the format dd/mm/yyy");
dob=sobj.next();
}
void display()
{
StringTokenizerst = new StringTokenizer(dob, "/");
System.out.print(cname+",");
while(st.hasMoreTokens())
{
String val = st.nextToken();
System.out.print(val);
if(st.countTokens()!=0)
System.out.print(","+" ");
}
}
}
OUTPUT
Enter Customer name:
Abhinava
Enter Customer DOB in the format dd/mm/yyy
01/07/1992
Customer Details
---------------------
Abhinava,01, 07, 1992
3 a. Write a Java program to read two integers a and b. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.
Import java.util.Scanner;
publicclassException_Divide
{
publicstaticvoid main(String[] args)
{
Scanner inputDevice = newScanner(System.in);
System.out.print("Please enter first number(numerator): ");
int numerator = inputDevice.nextInt();
System.out.print("Please enter second number(denominator): ");
int denominator = inputDevice.nextInt();
try {
newException_Divide().doDivide(numerator, denominator);
}
catch (Exception e)
{
System.out.println("Exception Condition Program is ending ");
}
}
publicvoiddoDivide(inta, int b) throws Exception
{
float result = a/b;
System.out.println("Division result of "+ a +"/"+b +"= " +result);
}
}
OUTPUT 1:
OUTPUT 2:
3. b Write a Java program that implements a multi-thread application that hash tree
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of cube of
the number.
Import java.util.Random;
Import java.util.Scanner;
class first extends Thread
{
public void run()
{
intnum=0;
Random r=new Random();
try
{
for(int i=0;i<=10;i++)
{
num=r.nextInt(10);
System.out.println("first thread generated num is ="+num);
Thread t2 = new Thread(new second(num));
t2.start();
Thread.sleep(1000);
Thread t3 = new Thread(new third(num));
t3.start();
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println(" ");
}
}
}
OUTPUT
4 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.
Import java.util.Random;
Import java.util.Scanner;
public class merge_sort
{
staticint max=30000;
public static void main(String[] args)
{
int a[]=new int[max];
longstart,end;
Scanner sobj=new Scanner (System.in);
System.out.println("********MERGE SORT ALGORITHM********");
System.out.println("Enter the no. of elements to be sorted :");
int n=sobj.nextInt();
Random rand=new Random();
for(int i=0;i<n;i++)
{
a[i]=rand.nextInt(100);
}
System.out.println("Array elements to be sorted are :");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
start=System.nanoTime();
mergesort(a,0,n-1);
end=System.nanoTime();
System.out.println("\nThe sorted elements are :");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.println("\nThe time taken to sort is "+(end-start)+"ns");
System.out.println("******************************************");
}//end of main
if(h>mid)
{
for(k=j;k<=high;k++)
{
Dept. of CS&E, PDIT, HOSAPETE Page 26
Design and Analysis of Algorithms Laboratory [18CSL47]
b[i]=a[k];
i=i+1;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i=i+1;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}//end of merge
}//end of class merge
OUTPUT 1:
********MERGE SORT ALGORITHM********
Enter the no. of elements to be sorted :
5
Array elements to be sorted are :
52 59 15 12 37
The sorted elements are :
12 15 37 52 59
The time taken to sort is 445502ns
******************************************
OUTPUT 2:
********MERGE SORT ALGORITHM********
Enter the no. of elements to be sorted :
10
Array elements to be sorted are :
17 92 59 22 36 8 62 27 95 47
The sorted elements are :
8 17 22 27 36 47 59 62 92 95
The time taken to sort is 870356ns
******************************************
Table that accounts the values for no of elements and time taken to sort
1 1000 96716619
2 5000 465834410
3 10000 931645022
4 15000 1379909926
5 20000 1868495032
5. 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 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
Import java.util.Random;
Import java.util.Scanner;
a[i]=a[j];
a[j]=temp;
}
}
OUTPUT 1:
********QUICK SORT ALGORITHM********
Enter the no. of elements to be sorted:
5
Array elements to be sorted are:
96 71 67 52 82
The sorted elements are:
52 67 71 82 96
The time taken to sort is 11899ns
******************************************
OUTPUT 2:
********QUICK SORT ALGORITHM********
Enter the no. of elements to be sorted:
10
Array elements to be sorted are:
96 9 33 35 16 38 37 7 66 98
The sorted elements are:
7 9 16 33 35 37 38 66 96 98
The time taken to sort is 16098ns
Table that accounts the values for no of elements and time taken to sort
1 1000 609634
2 5000 990393
3 10000 2115521
4 15000 4135854
5 20000 12681933
6 a) Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method.
Import java.util.Scanner;
Public classknapsackDP
{
publicvoid solve(int[] wt, int[] val, int W, int N)
{
inti,j;
int sol[][] = newint[N + 1][W + 1];
int selected[] = newint[N+1];
i=N;
j=W;
while (i>0&&j>0)
{
if (sol[i][j] !=sol[i-1][j])
{
selected[i] = 1;
j = j - wt[i];
}
i--;
}
for(i=1;i<=N;i++)
if (selected[i] == 1)
System.out.print(i +" ");
System.out.println();
}
OUTPUT 1:
Items selected :
134
Import java.util.Scanner;
Public class Fractional Knapsack
{
double weight[];
double profit[];
double ratio[];
double cap;
intnItems;
FractionalKnapsack()
{
Scanner scan = newScanner(System.in);
System.out.println("********* KNAPSACK PROBLEM-GREEDY METHOD *********");
System.out.println("Enter the number of items in the store: ");
nItems = scan.nextInt();
System.out.println("Enter the (weight and profit) of items: ");
weight = newdouble[nItems];
profit = newdouble[nItems];
ratio = newdouble[nItems];
for (int i = 0; i <nItems; ++i) {
weight[i] = scan.nextDouble();
profit[i] = scan.nextDouble();
ratio[i] = profit[i] / weight[i];
}
System.out.println("Enter the capacity of the knapsack: ");
cap = scan.nextDouble();
}
intgetNext()
{
double max = 0;
int index = -1;
for (int i = 0; i <profit.length; i++)
{
if (ratio[i] > max)
{
max = ratio[i];
index = i;
}
Dept. of CS&E, PDIT, HOSAPETE Page 35
Design and Analysis of Algorithms Laboratory [18CSL47]
}
return index;
}
void fill()
{
doublecW = 0; //current weight
doublecP = 0; //current profit
double select[]=newdouble[nItems];//marking item selection
while (cW< cap)
{
int item = getNext(); //next max ratio
if (item == -1)
{
//No items left
break;
}
if (cW + weight[item] <= cap)
{
cW += weight[item];
cP += profit[item];
ratio[item] = 0; //mark as used for the getNext() (ratio) function
select[item]=1;
}
else
{
select[item]=(cap-cW)/weight[item];
cP += (ratio[item] * (cap - cW));
cW += (cap - cW);
break; //the knapsack is full
}
}
System.out.println("\nItems Selected Fraction Selected(0/1/Partial) ");
System.out.println("************************************************");
for(int i=0;i<nItems;i++)
System.out.println("\t"+(i+1)+"\t\t"+select[i]);
System.out.println("\nMax Profit = " + cP + ", Max Weight = " + cW);
}
publicstaticvoid main(String[] args) {
FractionalKnapsackfk = newFractionalKnapsack();
Dept. of CS&E, PDIT, HOSAPETE Page 36
Design and Analysis of Algorithms Laboratory [18CSL47]
fk.fill();
}
}
OUTPUT 1:
********* KNAPSACK PROBLEM-GREEDY METHOD *********
Enter the number of items in the store:
3
Enter the (weight and profit) of items:
18 25
15 24
10 15
Enter the capacity of the knapsack:
20
OUTPUT 2:
********* KNAPSACK PROBLEM-GREEDY METHOD *********
Enter the number of items in the store:
3
Enter the (weight and profit) of items:
18 25
15 24
10 15
Enter the capacity of the knapsack:
20
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.
Import java.util.Scanner;
class Dijkstra
{
intn,src;
int a[][]=newint[10][10];
voidread_cost_adjacency_matrix()
{
System.out.println("********* DIJKSTRA'S ALGORITHM *********");
System.out.println("Enter no. of nodes :");
Scanner sobj=new Scanner (System.in);
n=sobj.nextInt();
System.out.println("Enter cost adjacency matrix :");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]=sobj.nextInt();
}
}
System.out.println("Enter source vertex :");
src=sobj.nextInt();
sobj.close();
}
voidfind_short_distance_path()
{
inti,j,v,min,u=0;
int d[]=newint[10];
int p[]=newint[10];
int s[]=newint[10];
for(i=1;i<=n;i++)
{
d[i]=a[src][i];
p[i]=src;
s[i]=0;
}
s[src]=1;
d[src]=0;
//find shortest distance & the path to other vertices
for(i=1;i<n;i++)
{
for(j=1,min=999;j<=n;j++)
{
if(s[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
}//end of j for loop
s[u]=1;
for(v=1;v<=n;v++)
{
if(s[v]==0 && d[u]+a[u][v]<d[v])
{
d[v]=d[u]+a[u][v];
p[v]=u;
}
}//end of v for loop
}//end of i for loop
System.out.println("The shortest path and distance is shown below:");
System.out.println("DEST VERTEX<-(Intermediate vertices)<-SOURCE=DISTANCE");
for(j=1;j<=n;j++)
{
if(d[j]==999)
System.out.println(j+"<-"+src+"="+d[j]);
elseif(d[j]==0)
System.out.println(j+"<-"+src+"="+d[j]);
else
{
i=j;
while(i!=src)
{
System.out.print(i+"<-");
Dept. of CS&E, PDIT, HOSAPETE Page 39
Design and Analysis of Algorithms Laboratory [18CSL47]
i=p[i];
}
System.out.println(i+"="+d[j]);
}
}//end of j for loop
}
}
publicclassShortest_path_dijkstra
{
publicstaticvoid main(String[] args)
{
Dijkstraob=newDijkstra();
ob.read_cost_adjacency_matrix();
ob.find_short_distance_path();
}
}
OUTPUT 1:
********* DIJKSTRA'S ALGORITHM *********
Enter no. of nodes :
6
Enter cost adjacency matrix :
0 15 10 999 45 999
999 0 15 999 20 999
20 999 0 20 999 999
999 10 999 0 35 999
999 999 999 30 0 999
999 999 999 4 999 0
Enter source vertex :
1
The shortest path and distance is shown below:
DEST VERTEX<-(Intermediate vertices)<-SOURCE=DISTANCE
1<-1=0
2<-1=15
3<-1=10
4<-3<-1=30
5<-2<-1=35
6<-1=999
OUTPUT 2:
********* DIJKSTRA'S ALGORITHM *********
Enter no. of nodes :
5
Enter cost adjacency matrix :
0 3 999 7 999
3 0 4 2 999
999 4 0 5 6
72504
999 999 6 4 0
Enter source vertex :
1
The shortest path and distance is shown below:
DEST VERTEX<-(Intermediate vertices)<-SOURCE=DISTANCE
1<-1=0
2<-1=3
3<-2<-1=7
4<-2<-1=5
5<-4<-2<-1=9
8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm. Implement the program in Java language.
Import java.util.Scanner;
Class Kruskal_algo
{
int n;
int a[][]=newint [10][10];
voidread_cost_adjacency_matrix()
{
System.out.println("********* KRUSKAL'S ALGORITHM *********");
System.out.println("Enter number of nodes");
Scanner scan=newScanner(System.in);
n=scan.nextInt();
for(int i=1;i<=n;i++)
{
parent[i]=i;
}
int count=0,sum=0, k=0,u=0,v=0;
while(count!=n-1)
{
int min=999;
for(int i=1;i<=n;i++)
Dept. of CS&E, PDIT, HOSAPETE Page 42
Design and Analysis of Algorithms Laboratory [18CSL47]
{
for(int j=1;j<=n;j++)
{
if(a[i][j]!=0 && a[i][j]<min)
{
min=a[i][j];
u=i;
v=j;
}
}
}
if(min==999)
break;
int i=u;
while(parent[i]!=i)
i=parent[i];
int j=v;
while(parent[j]!=j)
j=parent[j];
if(i!=j)
{
t[k][0]=u;
t[k][1]=v;
t[k][2]=min;
k++;
sum=sum+min;
parent[j]=i;
count++;
}
a[u][v]=a[v][u]=999;
}
if(count==n-1)
{
System.out.println("The min cost spanning tree with edges is");
System.out.println("*******************");
System.out.println("Edge"+"\t"+"Weight");
Dept. of CS&E, PDIT, HOSAPETE Page 43
Design and Analysis of Algorithms Laboratory [18CSL47]
System.out.println("*******************");
for(int i=0;i<n-1;i++)
System.out.println(t[i][0]+"->"+t[i][1]+"\t"+t[i][2]);
System.out.println("Cost of the Spanning tree="+sum);
}
else
System.out.println("Spanning tree does not exist");
}
}
publicclasskruskal
{
publicstaticvoid main(String[] args)
{
Kruskal_algo k=newKruskal_algo();
k.read_cost_adjacency_matrix();
k.find_minimum_spanningtree();
}
}
OUTPUT 1:
********* KRUSKAL'S ALGORITHM *********
Enter number of nodes
4
Enter the cost adjacency matrix
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0
The min cost spanning tree with edges is
*******************
Edge Weight
*******************
1->2 1
1->4 2
3->4 3
Cost of the Spanning tree=6
OUTPUT 2:
********* KRUSKAL'S ALGORITHM *********
Enter number of nodes
4
Enter the cost adjacency matrix
0 1 999 999
1 0 2 999
999 2 0 999
999 999 999 0
Spanning tree does not exist
9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm.
Implement the program in Java language.
Import java.util.Scanner;
Class Prims_algo
{
int n;
int a[][]=newint[10][10];
voidread_adjacency_matrix()
{
System.out.println("********* PRIMS ALGORITHM *********");
System.out.println("Enter number of nodes");
Scanner scan=newScanner(System.in);
n=scan.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]=scan.nextInt();
}
}
scan.close();
}
voidfind_minimum_spanning_tree()
{
intmin,u=0,v=0,k=0,count=0,cost=0,i,j;
int visited[]=newint[20];
int t[][]=newint[20][3];
visited[1]=1;
while(count!=(n-1))
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
Dept. of CS&E, PDIT, HOSAPETE Page 46
Design and Analysis of Algorithms Laboratory [18CSL47]
{
if(visited[i]==1 && visited[j]==0 && min > a[i][j])
{
min=a[i][j];
u=i;
v=j;
}
}
}
if(min==999)
break;
t[k][0]=u;
t[k][1]=v;
t[k][2]=min;
visited[v]=1;
cost+=min;
k++;
count++;
}//end of while
if(count==n-1)
{
System.out.println("The min cost spanning tree with edges is");
System.out.println("*******************");
System.out.println("Edge"+"\t"+"Weight");
System.out.println("*******************");
for(i=0;i<k;i++)
System.out.println(t[i][0]+"->"+t[i][1]+"\t"+t[i][2]);
System.out.println("************************");
System.out.println("cost of spanning tree="+cost);
System.out.println("************************");
}
else
System.out.println("spanning tree does not exist");
}
}
publicclass prim
{
publicstaticvoid main(String[] args)
Dept. of CS&E, PDIT, HOSAPETE Page 47
Design and Analysis of Algorithms Laboratory [18CSL47]
{
Prims_algo p=newPrims_algo();
p.read_adjacency_matrix();
p.find_minimum_spanning_tree();
}
}
OUTPUT 1:
********* PRIMS ALGORITHM *********
Enter number of nodes
4
Enter the cost adacency matrix
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0
The min cost spanning tree with edges is
*******************
Edge Weight
*******************
1->2 1
1->4 2
4->3 3
************************
cost of spanning tree=6
************************
OUTPUT 2:
********* PRIMS ALGORITHM *********
Enter number of nodes
4
Enter the cost adacency matrix
0 1 999 999
1 0 2 999
999 2 0 999
999 999 999 0
spanning tree does not exist
10 a. Write Java program to Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
Import java.lang.*;
Import java.util.Scanner;
Class Floyd
{
int d[][]=new int[10][10];
public void dis_path(int n, int a[][])
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=a[i][j];
}
}
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=Math.min(d[i][j],(d[i][k]+d[k][j]));
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(d[i][j]+" ");
}
System.out.println();
}
}
}
public class Floyed {
OUTPUT:
Import java.util.Scanner;
int i, j,cost;
int n = in.nextInt();
if(n==1)
System.exit(0);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
c[i][j] = in.nextInt();
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");
ccost, i, j, k;
if(start == n-1)
temp[j] = tour[j];
temp[start+1] = tour[i];
temp[i] = tour[start+1];
if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)
mintour[k] = temp[k];
tour[i] = mintour[i];
returnmincost;
OUTPUT :
0136
1023
3201
6310
0136
1023
3201
6310
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 subset
{
staticintc=0;
staticintw[]=newint[10];
staticintx[]=newint[10];
staticintn,d,i,sum=0;
for(i=0;i<n;i++)
sum=sum+w[i];
System.out.println("SUM="+sum);
if(sum<d || w[0]>d)
{
System.out.println("Subset is not possible!");
System.exit(0);
}
subset(0,0,sum);
if(c==0)
System.out.println("Subset is not possible!");
staticvoidsubset(intwsf,intk,inttrw )
{
int i;
x[k]=1;
if(wsf+w[k]==d)
{
System.out.println("Subset solution="+(++c));
for(i=0;i<=k;i++)
{
if(x[i]==1)
System.out.println(w[i]);
}
return;
}
if(wsf+w[k]+w[k+1]<=d)
subset(wsf+w[k],k+1,trw-w[k]);
OUTPUT
Enter number of elements:
5
Enter the elements in increasing order:
12345
Enter the value of d:
6
SUM=15
Subset solution=1
1
2
3
Subset solution=2
1
5
Subset solution=3
2
4
Import java.util.*;
Class Hamiltoniancycle
{
privateinta[][]=new int[10][10];
intx[]=new int[10];
intn;
publicHamiltoniancycle()
{
Scanner src = newScanner(System.in);
System.out.println("Enter the number of nodes");
n=src.nextInt();
for(inti=2;i<=n; i++)
x[i]=0;
for(inti=1;i<=n; i++)
for(intj=1; j<=n; j++)
a[i][j]=src.nextInt();
}
while(true)
{
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
return;
publicclass HamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycleobj=newHamiltoniancycle();
obj.getHCycle(2);
}
}
OUTPUT
Solution:
1265341
Solution:
1265431
Solution:
1326541
Solution:
1345621
Solution:
1435621
Solution:
1456231