Vtu 4th Sem Design and Analysis of Algorithm Observation
Vtu 4th Sem Design and Analysis of Algorithm Observation
BANGALORE
B.E IV Semester
Name: …………………..
USN: …………………...
EXP CONTENTS
NO.
A. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
1 (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.
B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
A. Design a super class 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.
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
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer
class considering the delimiter character as “/”.
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.
3
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.
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.
4 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.
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
5 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.
Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method
6 (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.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
8 algorithm. Use Union-Find algorithms in your program.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
9 algorithm.
Write Java programs to
10 (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
11 (a) 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 the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.
********************************************
Graduate Attributes
· Engineering Knowledge
· Problem Analysis
· Modern Tool Usage
· Conduct Investigations of Complex Problems
· Design/Development of Solutions
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
1 a. Create a Java class called Student with the following details as variables within it.
(v) USN
(vi) Name
(vii) Branch
(viii) 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.lang.*;
import java.util.*;
class STUDENT
{
String usn;
String name;
String branch;
long phno;
public void getdata()
{
Scanner read=new Scanner(System.in);
System.out. println("Enter USN,Name,Branch,PhNo");
usn=read.next();
name=read.next();
branch=read.next();
phno=read.nextLong();
}
public void display()
{
System.out. println("***************");
System.out .println("Student USN="+usn);
System.out .println("Student Name="+name);
System.out. println("Student Branch="+branch);
System.out .println("Student PhNo="+phno);
}
}
class PROGRAMA1
{
public static void main(String args[])
{
int n;
Scanner read=new Scanner(System.in);
System.out. println("Enter no of students");
n=read.nextInt();
STUDENT s[]= new STUDENT[n];
System.out.println("Enter the student deails");
for(int i=0;i<n;i++)
{
s[i]=new STUDENT();
s[i].getdata();
}
System.out.println(".....Student Details.....");
for(int i=0;i<n;i++)
{
s[i].display();
System.out.println();
}
}
}
OUTPUT:-
Enter no of students
2
Enter the student deails
Enter USN,Name,Branch,PhNo
129 aaa cs 9999
Enter USN,Name,Branch,PhNo
130 bbb cs 4444
.....Student Details.....
***************
student USN=129
student Name=aaa
student Branch=cs
student PhNo=9999
***************
student USN=130
student Name=bbb
student Branch=cs
student PhNo=4444
*****
1 b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
import java.lang.*;
import java.util.*;
class STACK
{
int st[]=new int[10];
int top;
int size;
STACK()
{
top=-1;
size=5;
}
void push(int item)
{
if(top==size-1)
System.out.println("Stack overflow...");
else
{
st[++top]=item;
}
}
void pop()
{
if(top==-1)
System.out.println("Stack underflow...");
else
{
System.out.println("Item popped=" +st[top--]);
}
}
void display()
{
if(top==-1)
Dept. of CSE,AMCEC 15CSL47 Page 7
Design and Analysis of Algorithm Laboratory
{
System.out.println("Stack Underflow");
}
else
{
for(int i=0;i<=top;i++)
{
System.out.println(+st[i]);
}
}
}
}
public class Program2
{
public static void main(String args[])
{
STACK Ob=new STACK();
Scanner read=new Scanner(System.in);
for(;;)
{
System.out.println("Enter 1:Push 2:Pop 3:Display 4:Exit");
int ch=read.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter item");
int item=read.nextInt();
Ob.push(item);
break;
case 2:
Ob.pop();
break;
case 3:
System.out.println("Stack contains...");
Ob.display();
break;
default:
return;1
}
}
}
}
OUTPUT:-
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
5
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
10
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
15
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
20
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
25
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
30
Stack overflow...
Enter 1:Push 2:Pop 3:Display 4:Exit
2a. Design a super class 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.
import java.util.Scanner;
class Staff
{
String StaffID,Name,Phone,Salary;
Scanner input = new Scanner(System.in);
void read()
{
System.out.println("Enter StaffID");
StaffID = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
System.out.println("Enter Salary");
Salary = input.nextLine();
}
void display()
{
System.out.printf("\n%-15s","STAFFID:");
System.out.printf("%-15s \n",StaffID);
System.out.printf("%-15s","NAME:");
System.out.printf("%-15s \n",Name);
System.out.printf("%-15s","PHONE:");
System.out.printf("%-15s \n",Phone);
System.out.printf("%-15s","SALARY:");
System.out.printf("%-15s \n",Salary);
}
}
class Teaching extends Staff
{
String Domain,Publication;
void read_Teaching()
{
super.read();
System.out.println("Enter Domain");
Domain = input.nextLine();
System.out.println("Enter Publication");
Publication = input.nextLine();
}
void display()
{
super.display();
System.out.printf("%-15s","DOMAIN:");
System.out.printf("%-15s \n",Domain);
System.out.printf("%-15s","PUBLICATION:");
System.out.printf("%-15s \n",Publication);
}
}
class Technical extends Staff
{
String Skills;
void read_Technical()
{
super.read();
System.out.println("Enter Skills");
Skills = input.nextLine();
}
void display()
{
super.display();
System.out.printf("%-15s","SKILLS:");
System.out.printf("%-15s \n",Skills);
}
}
class Contract extends Staff
{
String Period;
void read_Contract()
{
super.read();
System.out.println("Enter Period");
Period = input.nextLine();
}
void display()
{
super.display();
System.out.printf("%-15s","PERIOD:");
System.out.printf("%-15s \n",Period);
}
}
class Program2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of staff details to be created");
int n = input.nextInt();
Teaching steach[] = new Teaching[n];
Technical stech[] = new Technical[n];
Contract scon[] = new Contract[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter Teaching staff information");
steach[i] = new Teaching();
steach[i].read_Teaching();
}
for(int i=0;i<n;i++)
{
System.out.println("Enter Technical staff information");
stech[i] = new Technical();
stech[i].read_Technical();
}
for(int i=0;i<n;i++)
{
System.out.println("Enter Contract staff information");
scon[i] = new Contract();
scon[i].read_Contract();
}
System.out.println("\n STAFF DETAILS: \n");
System.out.println("-----TEACHING STAFF DETAILS-----");
for(int i=0;i<n;i++)
{
steach[i].display();
}
System.out.println();
input.close();
}
}
OUTPUT:
Enter number of staff details to be created
2
Enter Teaching staff information
Enter StaffID
1AM001
Enter Name
PALLAVI
Enter Phone
1111
Enter Salary
15000
Enter Domain
CSE
Enter Publication
5
Enter Teaching staff information
Enter StaffID
1AM002
Enter Name
KRITHIKA
Enter Phone
2222
Enter Salary
20000
Enter Domain
CSE
Enter Publication
3
Enter Technical staff information
Enter StaffID
1AM003
Enter Name
RITA
Enter Phone
3333
Enter Salary
15000
Enter Skills
JAVA
Enter Technical staff information
Enter StaffID
1AM004
Enter Name
RIYA
Enter Phone
4444
Enter Salary
15000
Enter Skills
PYTHON
Enter Contract staff information
Enter StaffID
1AM005
Enter Name
DEVI
Enter Phone
5555
Enter Salary
20000
Enter Period
5
Enter Contract staff information
Enter StaffID
1AM006
Enter Name
RAHUL
Enter Phone
6666
Enter Salary
15000
Enter Period
3
STAFF DETAILS:
STAFFID: 1AM001
NAME: PALLAVI
PHONE: 1111
SALARY: 15000
DOMAIN: CSE
PUBLICATION: 5
STAFFID: 1AM002
NAME: KRITHIKA
PHONE: 2222
SALARY: 20000
DOMAIN: CSE
PUBLICATION: 3
STAFFID: 1AM003
NAME: RITA
PHONE: 3333
SALARY: 15000
SKILLS: JAVA
STAFFID: 1AM004
NAME: RIYA
PHONE: 4444
SALARY: 15000
SKILLS: PYTHON
STAFFID: 1AM005
NAME: DEVI
PHONE: 5555
SALARY: 20000
PERIOD: 5
STAFFID: 1AM006
NAME: RAHUL
PHONE: 6666
SALARY: 15000
PERIOD: 3
BUILD SUCCESSFUL (total time: 1 minute 49 seconds)
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
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class
considering the delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
class Customer
{
String name,date_of_birth;
void readdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Customer name");
name=sc.next();
System.out.println("Enter date of birth in dd/mm/yyyy format");
date_of_birth=sc.next();
sc.close();
}
void display()
{
StringTokenizer st = new StringTokenizer(date_of_birth,"/");
System.out.println("The details of customer are");
System.out.print("<Name,DD,MM,YYYY>"+name);
while(st.hasMoreTokens())
System.out.print(","+st.nextToken());
}
}
public class Prgm2b
{
public static void main(String[] args)
{
Customer c = new Customer();
c.readdata();
c.display();
}
}
OUTPUT:-
Enter the Customer name
Ramya
Enter date of birth in dd/mm/yyyy format
10/12/1985
The details of customer are
<Name,DD,MM,YYYY>Ramya,10,12,1985BUILD SUCCESSFUL (total time: 22 seconds)
ALTERNATE PROGRAM
package customer;
import java.lang.*;
import java.util.*;
}
}
output:
Enter name&dob
zlatan
05/02/2000
Customer name=zlatan
customer date of birth=
05
02
2000
3a. 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.lang.*;
import java.util.*;
public class DIVIDE1
{
public static void main(String[] args)
{
int a,b,result;
Scanner read=new Scanner (System.in);
System.out.println("enter a&b");
a=read.nextInt();
b=read.nextInt();
try
{
result=a/b;
System.out.println("result="+result);
}
catch(Exception e)
{
System.out.println("Exception error="+e);
}
}
}
output:
enter a&b
40
2
result=20
output:-
enter a&b
50 0
Exception error=java.lang.ArithmeticException: / by zero
ALTERNATE PROAGRAM
import java.util.*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a,b,result;
Scanner s= new Scanner(System.in);
Run:
Enter the integer a and b
10
5
The result after division is2
BUILD SUCCESSFUL (total time: 7 seconds)
Run:
Enter the integer a and b
5
0
java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(Prgm3a.java:14)
BUILD SUCCESSFUL (total time: 4 seconds)
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 and prints; third thread will print the value of cube of the number.
import java.util.*;
import java.io.*;
class rand extends Thread
{
public int result;
static int num;
public int generate()
{
while(true)
{
try
{
display(sqnum(rand.num));
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println("Exception in Rand"+ex);
}
}
}
}
class cube extends Thread
{
public int cubenum(int a)
{
return(a*a*a);
}
public void display(int a)
{
System.out.println("Cube:"+a);
}
public void run()
{
while(true)
{
try
{
display(cubenum(rand.num));
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println("Exception in Rand"+ex);
}
}
}
}
public class Prgm3b
{
public static void main(String[] args) throws Exception
{
OUTPUT:-
Cube:91125
Square:3249
Random number:57
Square:3249
Random number:16
Cube:185193
Cube:4096
Random number:16
Square:256
Square:256
Cube:3375
Random number:15
Cube:3375
Random number:13
Square:225
Cube:2197
Square:169
Random number:56
Cube:175616
Random number:38
Square:0
Cube:54872
Square:1444
Random number:18
Cube:54872
Random number:45
Square:2025
ALTERNATE PROGRAM
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
void square()
{
Scanner read = new Scanner(System.in);
System.out.println("enter n");
n= read.nextInt();
System.out.println("squaring number="+(n*n));
}
}
{
Scanner read = new Scanner(System.in);
System.out.println("enter n");
n= read.nextInt();
System.out.println("cubing number="+(n*n*n));
}
}
public class AMC
{
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 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.*;
import java.util.Scanner;
public class program4
{
public static int partition(int a[],int low,int high)
{
int i=low+1, j=high, pivot=a[low];
while(i<=j)
{
while(a[i]<=pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
Swap(a,i,j);
}
}
Swap(a,low,j);
return j;
}
divide(a,low,j-1);
divide(a,j+1,high);
}
}
public static void main(String[] args)
{
int n,i;
int a[]=new int[500];
Scanner read = new Scanner(System.in);
Random rand = new Random();
System.out.println("Enter n");
n=read.nextInt();
System.out.println("Enter item");
for(i=0;i<n;i++)
{
a[i]=rand.nextInt(1000);
System.out.print(" " +a[i]);
}
System.out.println();
long t1=System.nanoTime();
divide(a,0,n-1);
long t2=System.nanoTime();
System.out.println("\nTime Taken=" +(t2-t1));
System.out.println("***Sorted Array***");
for(i=0;i<n;i++)
{
System.out.print(" " +a[i]);
}
}
}
OUTPUT:-
Enter n
5
Enter item
256 180 775 926 748
Time Taken=6935
***Sorted Array***
180 256 748 775 926BUILD SUCCESSFUL (total time: 2 seconds)
Enter n
10
Enter item
483 903 346 706 722 412 871 709 454 428
Time Taken=9432
***Sorted Array***
346 412 428 454 483 706 709 722 871 903BUILD SUCCESSFUL (total time: 3 seconds)
run:
Enter n
15
Enter item
257 765 751 826 857 274 34 143 521 667 790 302 857 507 895
Time Taken=10264
***Sorted Array***
34 143 257 274 302 507 521 667 751 765 790 826 857 857 895BUILD SUCCESSFUL (total
time: 3 seconds)
run:
Enter n
20
Enter item
244 255 917 852 370 332 673 316 980 769 596 372 346 711 785 70 950 930 748 498
Time Taken=11651
***Sorted Array***
70 244 255 316 332 346 370 372 498 596 673 711 748 769 785 852 917 930 950 980BUILD
SUCCESSFUL (total time: 4 seconds)
run:
Enter n
25
Enter item
662 229 440 260 743 183 740 315 32 493 524 528 174 954 446 40 870 161 43 140 504 834 734
113 285
Time Taken=12483
***Sorted Array***
32 40 43 113 140 161 174 183 229 260 285 315 440 446 493 504 524 528 662 734 740 743 834
870 954BUILD SUCCESSFUL (total time: 2 seconds)
ALTERNATE PROGRAM
import java.lang.*;
import java.util.*;
public class QSORT
{
public static int partition(int a[], int low, int high)
{
int pivot=a[low], i=low+1,j=high;
while(i<=j)
{
while(a[i]<=pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
swap(a,i,j);
}
}
swap(a,low,j);
return j;
}
public static void swap(int a[],int x, int y)
{
int temp=a[x];
a[x]=a[y];
a[y]=temp;
}
public static void divide(int a[],int low, int high)
{
if(low<high)
{
int j=partition(a,low,high);
divide(a,low,j-1);
divide(a,j+1,high);
}
}
long t1=System.nanoTime();
divide(a,0,n-1);
long t2=System.nanoTime();
System.out.println("***sorted list***");
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}
System.out.println();
System.out.println("Time taken= "+(t2-t1));
}
}
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 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.lang.*;
import java.util.*;
import java.util.concurrent.*;
}
}
public static void merge(int a[],int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
int b[]=new int[5000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
}
}
while(i<=mid)
{
b[k++]=a[i++];
while(j<=high)
{
b[k++]=a[j++];
}
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}
Output:
Enter n
5
817 289 189 368 104
***** SORTED LIST ****
104 189 289 368 817
TIME TAKEN FOR THE MERGE SORT in nano sec=30792.0
Which is 3.0792E-6 Seconds
Enter n
10
971 683 294 547 617 852 532 340 359 386
***** SORTED LIST ****
294 340 359 386 532 547 617 683 852 971
TIME TAKEN FOR THE MERGE SORT in nano sec=59363.0
Which is 5.9363E-6 Seconds
OR
package mgsortb2;
import java.lang.*;
import java.util.*;
}
}
public static void merge(int a[],int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
int b[]=new int[5000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
}
}
while(i<=mid)
{
b[k++]=a[i++];
}
while(j<=high)
{
b[k++]=a[j++];
}
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}
System.out.println();
System.out.println("TIME TAKEN FOR THE MERGE SORT="+(t2-t1));
6. Implement in Java, the 0/1 Knapsack problem using: a. Dynamic Programming method
import java.lang.*;
import java.util.*;
else if(w[i]>j)
{
v[i][j]=v[i-1][j];
}
else
{
v[i][j]=max(v[i-1][j],p[i]+v[i-1][j-w[i]]);
}
}
}
}
void display()
{
System.out.println("* * * * * * * * * * * * *");
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
System.out.print(" "+v[i][j]);
}
System.out.println();
}
System.out.println("Optimal solution= "+v[n][m]);
}
public static void main(String args[])
{
KNAPSACKB ob=new KNAPSACKB();
ob.getdata();
ob.optimal();
ob.display();
}
}
output:-
Enter number of items
5
Enter weight of each item
2
3
1
4
2
Enter profit of each item
20
40
15
30
25
Enter maximum capacity
6
*************
0000000
0 0 20 20 20 20 20
0 0 20 40 40 60 60
0 15 20 40 55 60 75
0 15 20 40 55 60 75
0 15 25 40 55 65 80
Optimal solution= 80
}
System.out.println("enter profit of each item");
for(int i=0;i<n;i++)
{
p[i]=read.nextFloat();
}
System.out.println("enter max capacity");
m=read.nextFloat();
}
void optimal()
{
int i;
float rem;
for( i=1;i<n;i++)
{
x[i]=0;
rem=m; sum=0;
for(i=0;i<n;i++)
{
if(w[i]>rem)
break;
x[i]=1;
sum=sum+p[i];
rem=rem-w[i];
}
if(i<=n)
{
x[i]=rem/w[i];
sum=sum+(rem/w[i]*p[i]);
}
}
void display()
{
System.out.println("optimal sloution="+sum);
System.out.println("item selected weight and profit");
for(int i=1;i<n;i++)
{
System.out.print(x[i]*w[i]);
System.out.print(" "+x[i]*p[i]);
System.out.println();
}
}
Output:
Enter the number of items
4
enter item with decsending order density
enter the weight of each item
10
12
13
14
enter profit of each item
20
22
25
36
enter max capacity
40
optimal sloution=79.85715
item selected weight and profit
12.0 22.0
13.0 25.0
5.0 12.857143
BUILD SUCCESSFUL (total time: 28 seconds)
OR
import java.lang.*;
import java.util.*;
public class KNAPSACK8
{
int n,i;
float m,sum;
float W[]=new float[10];
float P[]=new float[10];
}
void display()
{
System.out.println("Optimal solution="+sum);
System.out.println("Item selected with weight-profit");
for(i=1;i<=n;i++)
{
System.out.println(x[i]*W[i]+" "+x[i]*P[i]);
}
}
public static void main(String args[])
{
KNAPSACK8 ob=new KNAPSACK8();
ob.getdata();
ob.optimal();
ob.display();
}
}
output:-
Enter number of items
5
Enter item descending order by density
Enter weight of each item
3
2
5
6
8
Enter profit of each item
8
4
8
6
2
Enter the maximum capacity
12
Optimal solution=22.0
Item selected with weight-profit
3.0 8.0
2.0 4.0
5.0 8.0
2.0 2.0
0.0 0.0
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.*;
public class DijkstraDemoo
{
public static int min(int a,int b)
{
if(a<b)
return a;
else
return b;
}
public static boolean check(int[] v,int n)
{
for(int i=1;i<n+1;i++)
{
if(v[i]!=1)
return
true;
}
return false;
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the number of nodes in graph");
int n=s.nextInt();
int i,j;
int graph[][]=new int[n+1][n+1];
int visited[]=new int[n+1];
int d[]=new int[n+1];
TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();
System.out.println("enter cost adajency matrix for graph,if 2 nodes are not connected enter
999");
for(i=1;i<n+1;i++)
{
for(j=1;j<n+1;j++)
graph[i][j]=s.nextInt();
}
for(i=1;i<n+1;i++)
{
visited[i]=0;
d[i]=999;
}
System.out.println("enter the source vertsx");
int source=s.nextInt();
visited[source]=1;
d[source]=0;
int u=source;
int v,a=0;
do
{
for(v=1;v<n+1;v++)
{
if(graph[u][v]!=999 && visited[v]!=1 && graph[u][v]!=0)
{
d[v]=min(d[v],(d[u]+graph[u][v]));
map.put(d[v],v);
}
}
u=map.firstEntry().getValue();
visited[u]=1;
map.clear();;
}
while(check(visited,n));
for(i=1;i<n+1;i++)
System.out.println("distance from source to "+i+" is"+d[i]);
}
}
run:
enter the number of nodes in graph
6
enter cost adajency matrix for graph,if 2 nodes are not connected enter 999
0 9 7 7 999 1
9 0 999 2 9 3
7 999 0 3 6 999
7 2 3 0 10 999
999 9 6 10 0 7
1 3 999 999 7 0
enter the source vertsx
1
distance from source to 1 is0
distance from source to 2 is4
distance from source to 3 is7
distance from source to 4 is6
distance from source to 5 is8
distance from source to 6 is1
OR
import java.lang.*;
import java.util.*;
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("enter the number of nodes");
n=read.nextInt();
System.out.println("enter the cost matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=read.nextInt();
}
}
System.out.println("enter the source");
source=read.nextInt();
for(int i=0;i<n;i++)
{
visited[i]=0;
}
}
void shortest()
{
int i,j,u=0,v=0,min;
for(i=0;i<n;i++)
{
path[i]=d[source][i];
visited[source]=1;
for(i=1;i<n;i++)
{
min=999;
for(j=1;j<n;j++)
{
if(path[i]<min && visited[j]==0)
{
min=path[j];
u=j;
}
}
visited[u]=1;
for(v=0;v<n;v++)
{
if(path[u]+d[u][v]<path[v]&&visited[v]==0)
{
path[v]=path[u]+d[u][v];
}
}
}
void display()
{
System.out.println("*** Shortest path***");
for(int i=0;i<n;i++)
{
System.out.println(source+"-"+i+"="+path[i]);
}
}
public static void main(String[] args)
{
Dijkstra ob=new Dijkstra();
ob.getdata();
ob.shortest();
ob.display();
Output:
Enter the number of nodes
6
enter the cost matrix
0 9 7 7 999 1
9 0 999 2 9 3
7 999 0 3 6 999
7 2 3 0 10 999
999 9 6 10 0 7
1 3 999 999 7 0
enter the source
1
*** Shortest path***
1-0=4
1-1=0
1-2=5
1-3=2
1-4=9
1-5=3
8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.
package krush;
import java.lang.*;
import java.util.*;
v = j;
}
}
}
if(find(u)!=find(v))
{
System.out.println(u+"-"+v+"="+d[u][v]);
parent[v]=u;
ne++;
sum=d[u][v]+sum;
}
d[u][v]=d[v][u]=999;
}
System.out.println("minmum spanning tree cost="+ sum);
}
int find (int x)
{
while(x!=parent[x])
{
x=parent[x];
}
return x;
}
output:
Enter the number nodes
6
Enter cost matrix
0 35 999 30 999 999
35 0 10 38 90 999
999 10 0 999 40 50
30 38 999 0 20 999
999 90 40 20 0 45
999 999 50 999 45 0
******** minimum spanning tree ********
1-2=10
3-4=20
0-3=30
0-1=35
4-5=45
minmum spanning tree cost=140
9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.
import java.lang.*;
import java.util.*;
public class PRIMSA
{
int n,ne,sum;
int d[][]=new int[10][10];
int visited[]=new int[10];
void getdata()
{
int i,j;
Scanner read=new Scanner(System.in);
System.out.println("Enter number of nodes");
n=read.nextInt();
System.out.println("Enter cost matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
d[i][j]=read.nextInt();
}
}
for(i=0;i<n;i++)
{
visited[i]=0;
}
}
void spantree()
{
int i,j,u=0,v=0,min;
ne=0;
sum=0;
visited[0]=1;
while(ne!=n-1)
{
min=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(d[i][j]<min)
{
if(visited[i]==1&&visited[j]==0)
{
min=d[i][j];
u=i;
v=j;
}
}
}
}
System.out.println(u+"---"+v+"="+d[u][v]);
ne++;
sum=sum+d[u][v];
visited[v]=1;
}
System.out.println("Cost of minimum spanning tree="+sum);
}
Output:
OR
import java.util.Scanner;
class Prim
{
public static void my_prim(int[][] adj, int N)
{
int i,j,nv,min,min_cost=0,u=0,v=0;
int[] visit=new int[N];
for(i=0;i<N;i++)
{
visit[i]=-0;
}
visit[0]=1;
nv=1;
while(nv<N)
{
min=999;
for(i=0;i<N;i++)
{
if(visit[i]==1)
{
for(j=0;j<N;j++)
{
if(adj[i][j]<min)
{
min=adj[i][j];
adj[i][j]=999;
u=i;
v=j;
}
}
}
}
if(visit[u]==1 && visit[v]==0)
{
visit[v]=1;
min_cost+=min;
nv++;
System.out.printf("Edge %d - %d: (%d)\n",u,v,min);
}
}
System.out.println("Cost:" +min_cost);
}
}
public class Prgm9
{
10. Write Java programs to implement All-Pairs Shortest Paths problem using
a. Floyd's algorithm.
import java.lang.*;
import java.util.*;
public class FLOYD {
int n;
int D[][]=new int[5][5];
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter number of nodes");
n=read.nextInt();
System.out.println("Enter cost matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
D[i][j]=read.nextInt();
}
}
}
void shortest()
{
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
D[i][j]=min(D[i][j],D[i][k]+D[k][j]);
}
}
}
}
void display()
{
System.out.println("*****All pair shortest path*****");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(" "+D[i][j]);
Dept. of CSE,AMCEC 15CSL47 Page 54
Design and Analysis of Algorithm Laboratory
}
System.out.println();
}
}
int min(int x,int y)
{
if(x<y)
{
return x;
}
else
{
return y;
}
}
output:-
import java.util.Scanner;
int min=999;
for(i=0;i<n;i++)
{
if(d[u][i]<min && visited[i]==0)
{
min=d[u][i];
v=i;
}
}
return v;
}
void display()
{
System.out.println("cost of tsp="+sum);
}
OUTPUT:
enter no of nodes
4
enter cost matrix
0 30 10 90
30 0 100 20
10 100 0 5
90 20 5 0
TSP path..........
0---->2---->3---->1---->0
cost of tsp=65
OR
import java.util.Scanner;
public class MyTSP1
{
static int MAXVERT=10;
static int MAXSUBSET=1024;
}
table[n][set]=min;
}
return table[n][set];
}
public static void main(String args[])
{
int i,j;
int[][] mat=new int[MAXVERT][MAXVERT];
Scanner sc=new Scanner(System.in);
System.out.printf("Enter the number of vertices :\n");
MAXVERT=sc.nextInt();
System.out.printf("Enter cost matrix :\n");
for(i=0;i<MAXVERT;i++)
for(j=0;j<MAXVERT;j++)
mat[i][j]=sc.nextInt();
System.out.printf("The minimum cost is %d \n",TSP(MAXVERT,mat));
return;
}
}
OUTPUT:-
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;
class subset
{
int s[],x[];
int d,n;
subset()
{
s=new int[10];
x=new int[10];
}
void read()
{
int sum=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter the total number of elements in set");
n=in.nextInt();
System.out.println("Enter the set");
for(int i=1;i<=n;i++)
s[i]=in.nextInt();
System.out.println("Enter the maximum set value");
d=in.nextInt();
for(int i=1;i<=n;i++)
sum=sum+s[i];
if(sum<d)
System.out.println("The sets are");
subset_fun(0,1,sum);
in.close();
}
void subset_fun(int S,int k,int r)
{
x[k]=1;
if((S+s[k])==d)
{
for(int i=1;i<=k;i++)
if(x[i]==1)
System.out.println(+s[i]+" ");
System.out.println();
}
else
if(S+s[k]+s[k+1]<=d)
subset_fun(S+s[k],k+1,r-s[k]);
if((S+r-s[k]>=d)&&(S+s[k+1]<=d))
{
x[k]=0;
subset_fun(S,k+1,r-s[k]);
}
}
}
OUTPUT:-
Enter the total number of elements in set
5
Enter the set
12568
Enter the maximum set value
9
1
2
6
1
8
OR
import java.lang.*;
import java.util.*;
public class SUBSETT
{
int n,d;
int s[]=new int[10];
int visited[]=new int[10];
void getdata()
{
int i,sum=0;
Scanner read=new Scanner(System.in);
ob.getdata();
output:-
enter the number of elements
5
enter elements
12356
enter d=
8
subset=
125
subset=
26
subset=
356
12. Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.
import java.util.Arrays;
import java.util.Scanner;
public class hamildemo
{
int count;
int path=1;
void swap(int[] arr,int x,int y)
{
int temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
void permute(int[] arr,int[][] G)
{
permute(arr,0,arr.length-1,G);
}
void permute(int[] arr,int i,int n,int[][] cost)
{
int j;
if(i==n)
{
hamilcycle(arr,cost);
}
else
{
for(j=i;j<=n;j++)
{
swap(arr,i,j);
permute(arr,i+1,n,cost);
swap(arr,i,j);
}
}
}
void hamilcycle(int a[],int[][] G)
{
count=0;
for(int i=0;i<a.length-1;i++)
{
if(G[a[i]][a[i+1]]!=0)
count++;
}
if(count==a.length-1&&G[a[a.length-1]][a[0]]==1)
{
System.out.println("Cycle No "+path+"-->");
for(int i=0;i<a.length;i++)
System.out.println(a[i]+" ");
System.out.println(a[0]);
System.out.println();
path++;
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of nodes in graph");
int n=s.nextInt();
int graph[][]=new int[n][n];
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
graph[i][j]=s.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=i;
System.out.println("All possible Hamiltonian Cycles in graph");
new hamildemo().permute(arr,graph);
}
}
run:
Enter the number of nodes in graph
5
Enter the adjacency matrix
01011
10110
01001
11001
10110
All possible Hamiltonian Cycles in graph
Cycle No 1-->
0
1
2
4
3
0
Cycle No 2-->
0
3
1
2
4
0
Cycle No 3-->
0
3
4
2
1
0
Cycle No 4-->
0
4
2
1
3
0
Cycle No 5-->
1
0
3
4
2
1
Cycle No 6-->
1
2
4
3
0
1
Cycle No 7-->
1
2
4
0
3
1
Cycle No 8-->
1
3
0
4
2
1
Cycle No 9-->
2
1
0
3
4
2
Cycle No 10-->
2
1
3
0
4
2
Cycle No 11-->
2
4
0
3
1
2
Cycle No 12-->
2
4
3
0
1
2
Cycle No 13-->
3
1
2
4
0
3
Cycle No 14-->
3
0
1
2
4
3
Cycle No 15-->
3
0
4
2
1
3
Cycle No 16-->
3
4
2
1
0
3
Cycle No 17-->
4
2
1
3
0
4
Cycle No 18-->
4
2
1
0
3
Cycle No 19-->
4
3
0
1
2
4
Cycle No 20-->
4
0
3
1
2
4
import java.io.*;
class GFG
{
// Function print matrix in spiral form
static void spiralPrint(int m, int n, int a[][])
{
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/
k++;
// driver program
public static void main (String[] args)
{
int R = 3;
int C = 6;
int a[][] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};
spiralPrint(R,C,a);
}
}
import java.util.*;
import java.math.*;
class CheckPrimeTest
{
//Function to check and return prime numbers
static boolean checkPrime(long n)
{
// Converting long to BigInteger
BigInteger b = new BigInteger(String.valueOf(n));
return b.isProbablePrime(1);
}
// Driver method
public static void main (String[] args)
throws java.lang.Exception
{
long n = 13;
System.out.println(checkPrime(n));
}
}
$ javac Bin_Packing_Algorithm.java
$ java Bin_Packing_Algorithm
BIN - PACKING Algorithm
Enter the number of items in Set:
8
Enter 8 items:
45834516
Enter the bin size:
10
import java.util.*;
import java.lang.*;
import java.io.*;
int V, E;
Edge edge[];
graph.BellmanFord(graph, 0);
}
}
import java.io.*;
class MultistageGraph
{
public static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
int r = findR(j+1);
cost[j] = G[j][r]+cost[r];
d[j] = r;
}
p[1] = 1; p[k] = n;
for(int j = 2; j<k; j++)
p[j] = d[p[j-1]];
System.out.print(d[1]+"-");
for(int j=2; j<=n; j++)
{
if((d[j] == d[j-1]) || (d[j] == 0))
continue;
System.out.print(d[j]+"-");
}
System.out.print(n);
}
static int findR(int cu)
{
int r1 = n+1;
for(int h =1; h<=n; h++)
{
if( (G[h][cu] != 0) && ( r1 == n+1 ) )
{
r1 = h;
continue;
}
if (G[h][cu] != 0)
{
if(G[h][cu] < G[r1][cu] )
r1 = h;
}
}
return r1;
}
}
7. N- QUEEN PROBLEM
return true;
feasible solutions.*/
boolean solveNQ()
{
int board[][] = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if (solveNQUtil(board, 0) == false)
{
System.out.print("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
//Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
Arrays.fill(available, true);
// Driver method
public static void main(String args[])
{
Graph g1 = new Graph(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
System.out.println("Coloring of graph 1");
g1.greedyColoring();
System.out.println();
Graph g2 = new Graph(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
System.out.println("Coloring of graph 2 ");
g2.greedyColoring();
}
}
9. A Java program for Floyd Warshall All Pairs Shortest Path algorithm.
import java.util.*;
import java.lang.*;
import java.io.*;
class AllPairShortestPath
{
final static int INF = 99999, V = 4;
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
AllPairShortestPath a = new AllPairShortestPath();
// Driver code
public static void main(String[] args) {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = keys.length;
System.out.println("Cost of Optimal BST is " +
optimalSearchTree(keys, freq, n));
}
}
VIVA QUESTIONS
What is an algorithm?
An algorithm is finite set of instructions that is followed, accomplishes a particular task.
All algorithms must satisfy the following criteria:
• Input
• Output
• Definiteness
• Finiteness
• Effectiveness
Define space complexity?
The space complexity can be defined as amount of memory required by an algorithm to
run.
Define time complexity?
The time complexity of an algorithm is the amount of time required by an algorithm to run
to completion.
What are the desirable properties of an algorithm?
• Simplicity: designing algorithms that are simpler to understand and code.
• Generality:
Worst Case: The key is the last element in the array or the key is not in the array
# of comparisons: n = O(n) and Θ(n)
Average Case: The key is equally likely to be in any position in the array
If the key is in the first array position: 1 comparison
Pattern: happy
Text: It is never too late to have a happy childhood.
Divide & conquer is a general algorithm design strategy with a general plan as follows:
DIVIDE: A problem‘s instance is divided into several smaller instances of the same
problem, ideally of about the same size.
RECUR: Solve the sub-problem recursively.
CONQUER: If necessary, the solutions obtained for the smaller instances are combined to
get a solution to the original instance.
Quick
Array O(n log(n)) O(n log(n)) O(n^2) O(log(n))
Sort
O(n)
Merge
Array O(n log(n)) O(n log(n)) O(n log(n))
sort
Bubble
Array O(n) O(n^2) O(n^2) O(1)
sort
Insertion
Array O(n) O(n^2) O(n^2) O(1)
sort
Selection
Array O(n^2) O(n^2) O(n^2) O(1)
sort
Breadth-first search (BFS) is a strategy for searching in a graph when search is limited to
essentially two operations: (a) visit and inspect a node of a graph; (b) gain access to visit
the nodes that neighbor the currently visited node. The BFS begins at a root node and
inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it
inspects their neighbor nodes which were unvisited, and so on.
Topological sort
A topological sort or topological ordering of a directed graph is a linear ordering of
its vertices such that for every directed edge uv from vertex u to vertex v, u comes
before v in the ordering.
Tree edge: whenever a new unvisited vertex is reached for the first time, the vertex is
attached as a child to the vertex it is being reached from with an edge called a tree edge.
Cross edge: If an edge leading to a previously visited vertex other than its immediate
predecessor is encountered, the edge is noted as a cross edge.
Hamiltonian circuit: a path that starts and ends at the same vertex and passes through all
other vertices exactly once
Subset-Sum Problem: The problem of finding a subset of a given set S = {s1, ……, sn} of
n positive integers whose sum is equal to a given positive integer d.
Travelling salesman problem: find the shortest Hamiltonian circuit in a complete graph
with positive integer
Knapsack problem: Problem of finding 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.