18csl47 Lab Manual
18csl47 Lab Manual
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 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.
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 “/”.
3.
a. Write a Java program to read two integers a andb . Computea /b and print, whenb is not
zero.Raise an exception whenb 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 andprints; third thread will print the value of cube
of the number.
Sort a given set ofn 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
4. to sort. Plot a graph of the time taken versus non graph sheet. The elements can
be read from a fileor 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 ofn 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.
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
verticesusing Dijkstra'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.
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
undirectedGraph G ofn vertices using backtracking principle.
C
H
A
P
TE
R
1
INTRODUCTION
N
e
e
d
f
or
s
t
ud
y
i
ng
a
l
g
or
i
t
hm
sT
h
e
o
r
et
i
c
al
i
m
po
rt
a
n
ce
The study of algorithms is the concepts of computer science.
It is a standard set of important algorithms, they further our analytical skills&
help usin developing new algorithms for required applications
A
l
g
or
i
t
hm
An algorithm is a sequence of unambiguous instructions for solving a problem,
i.e., forobtaining a required output for any legitimate input in a finite amount of time.
I
n
ad
di
t
i
on
,
al
l
al
g
or
i
t
hm
sm
u
s
t
s
at
i
s
f
yt
he
f
o
l
l
ow
i
ng
c
ri
t
e
ri
a
:
1
.I
n
pu
t
: E
a
c
h
al
g
or
i
t
hm
sh
o
u
l
dh
a
ve
z
e
r
oo
r
m
or
e
in
p
u
ts
.
T
he
range ofinput for which algorithms works should be
specified carefully.
2
.O
ut
p
u
t: T
h
e
a
l
go
r
i
t
hm
sh
o
u
l
dp
r
od
u
c
ec
o
r
r
e
ct
r
e
su
l
t
s.
A
tl
e
as
to
n
e
quantityhas to be produced.
3
.D
ef
i
n
i
te
ne
s
s
:E
a
ch
i
n
st
r
uc
t
i
o
ns
ho
u
l
d
bec
l
e
ar
an
d
u
na
m
b
i
gu
o
us
.
4
.E
f
fe
c
t
i
v
en
e
ss
:
E
ve
ry
i
n
st
r
uc
t
i
o
ns
ho
u
l
d
bes
i
m
pl
ea
n
ds
h
o
u
l
dt
r
a
ns
f
o
rm
t
h
e
given Inputto the desired output. so that it can be carried out, in
5
.F
i
ni
t
e
ne
ss
:I
fw
e
tr
a
c
eo
u
tt
h
ei
n
st
r
uc
t
i
o
no
fa
n
a
l
go
r
i
t
hm
,t
h
e
nf
o
ra
l
l
cases, thealgorithm must terminates after a finite number
ofsteps.
N
o
t
i
o
no
fa
l
g
or
i
t
hm
Problem
Algorithm
Input
“Computer”
Page 1
DAA LAB 18CSL4
O
u
t
p
u
t
Page 2
DAA LAB 18CSL4
F
u
n
d
am
e
n
t
al
s
of
Al
g
or
i
t
hm
i
cp
r
ob
l
e
ms
ol
v
i
ng
• Understanding the problem
• Ascertain the capabilities of the computational device
• Exact /approximate solution.
• Decide on the appropriate data structure
• Algorithm design techniques
• Methods of specifying an algorithm
• Proving an algorithms correctness
• Analyzing an algorithm
I
m
po
r
ta
n
t
P
r
ob
l
em
Ty
p
e
s
of
d
i
ff
e
r
en
t
c
at
e
g
or
i
e
s
•S
o
r
t
i
n
g
It refers to the problem of re-arranging the items of a given list in ascending or
descending order. The various algorithms that can be used for sorting are bubble sort,
selection sort, insertion sort, quick sort, merge sort, heap sort etc.
•S
e
a
r
c
hi
n
g
This problem deals with finding a value, called a search key, in a given set.
The various algorithms that can be used for searching are
binarysearch, linear search, hashing, interpolation search etc.
•S
t
r
i
n
gp
ro
c
e
s
s
in
g
This problem deals with manipulation of characters or strings, string
matching,search and replace, deleting a string in a text etc.
String processing algorithm such as string matching algorithms is
used in thedesign of assemblers and compliers.
•G
r
a
p
hp
r
ob
l
e
ms
The graph is a collection of vertices and edges.
Page 3
DAA LAB 18CSL4
•C
o
m
b
i
na
t
o
ri
a
lp
r
ob
l
e
ms
These problems are used to find combinatorial object such as permutation
andcombinations.
Ex: travelling salesman problem, graph coloring problem etc
•G
e
o
m
e
tr
i
c
pr
ob
l
e
ms
This problem deal with geometric objects such as points, curves, lines,
polygon etc.Ex: closest-pair problem, convex hull problem
•N
u
m
e
r
i
ca
l
p
ro
bl
e
ms
These problems involving mathematical manipulations solving equations,
computing differentiations and integrations, evaluating various types of
functionsetc.
Ex: Gauss elimination method, Newton-Rap son method
F
u
n
d
am
e
n
t
al
s
of
da
t
a
St
r
u
ct
u
r
es
Since most of the algorithms operate on the data, particular ways of arranging
the dataplay a critical role in the design & analysis of algorithms.
A data structure can be defined as a particular way of arrangement of data.
T
h
e
c
om
m
o
n
ly
u
s
ed
d
a
t
as
t
r
u
ct
u
r
es
a
re
:
1. Linear data structures
2. Graphs
3. Trees.
4. Sets and dictionaries
1. L
i
n
ea
rd
a
t
a
s
tr
u
ct
u
r
es
The most common linear data structures are arrays and linked lists.
Arrays: Is a collection of homogeneous items. An item’s place within the
collection iscalled an index.
Linked list: finite sequence of data itemsi.e.it is a collection of data items in a certain order.
2. G
r
a
p
hs
A data structure that consists of a set of nodes and a set of edges that relate
the nodesto each other is called a graph.
Page 4
DAA LAB 18CSL4
3. T
r
e
e
A tree is a connected acyclic graph that has no cycle.
4. S
e
t
s
a
nd
di
c
t
io
na
r
i
e
s
Asetisdefinedasanunorderedcollectionofdistinctitemscalledanelementoftheset
Dictionary is a data structure that implements searching, adding of objects
A
n
a
l
y
si
s
of
al
g
or
i
t
hm
s
T
h
e
o
r
et
i
c
al
a
na
l
ys
i
s
of
ti
m
ee
ff
i
c
i
en
cy
Algorithm efficiency depends on the input size n. And for some algorithms
efficiencydepends on type of input.
W
e
h
a
v
eb
e
s
t
,w
o
rs
t
&
av
e
ra
g
e
c
as
e
e
f
fi
c
i
en
ci
e
s
W
o
r
s
t
-
ca
s
ee
f
f
i
c
ie
n
cy
:
Efficiency (number of times the basic operation will be executed) for the worst
caseinput of size n.i.e. The algorithm runs the longest among all possible inputs
of size n.
B
e
s
t
-
c
as
e
ef
f
i
c
ie
n
cy
:
Efficiency (number of times the basic operation will be executed for the best
caseinput of size n.i.e. The algorithm runs the fastest among all possible inputs of
size n.
Page 5
DAA LAB 18CSL4
A
v
e
r
a
ge
-
c
a
se
ef
f
i
c
ie
n
cy
:
Average time taken (number of times the basic operation will be executed) to
solve all thepossible instances (random) of the input.
A
s
y
m
p
to
t
i
c
No
ta
t
i
o
ns
Asymptotic notation is a way of comparing functions that ignores
constant factorsand small input sizes.
Three notations used to compare orders of growth of an algorithm’s basic operation are:
O
,
Ω,
θn
ot
a
t
i
on
s
.
B
i
g
-
ohn
o
t
a
t
i
on
:
A function t(n) is said to be in O(g(n)),denoted t(n)€O(g(n)),if t(n) is bounded above
by someconstant multiple of g(n) for all large n i.e., if there exist some positive
constant c and some
nonnegative integer n۪ 0 such that t (n)<=cg(n) for all n>= n0
B
i
g
-
ohn
o
t
a
t
i
on
t
(n
)
€
O
(g
(
n
)) B
i
g
-
ome
g
a
n
ot
a
t
i
on
t
(n
)
€
Ω
,(
g
(
n)
)
B
i
g
-
ome
g
a
n
ot
a
t
i
on
:
A function t(n) is said to be in Ω(g(n)),denoted t(n)€ Ω(g(n)),if t(n) is bounded
below bysome constant multiple of g(n) for all large n i.e., if there exist some positive
constant c and
some nonnegative integer n۪ 0 such that
t
(
n
)
>=
c
g(
n
)
fo
r
n
>
a
l
l=
nB
i
g
-
0t
h
et
a
no
t
a
ti
o
n:
A function t(n) is said to be in θ(g(n)),denoted t(n)€ θ(g(n)),if t(n) is bounded
both above and below by some positive constant multiple of g(n) for all large n i.e., if
there existsome positive constantc
Page 6
DAA LAB 18CSL4
B
i
g
-
th
et
a
no
t
a
ti
o
nt
(
n)
€
θ
(g
(
n
))
B
a
s
i
c
As
ym
p
t
o
t
i
cE
f
fi
c
i
en
cy
c
l
a
ss
e
s:
1 c
o
n
s
t
an
t
l
o
gn l
o
ga
r
it
h
mi
c
N l
i
n
ea
r
n
l
o
gn n
l
o
gn
n2 q
u
a
d
r
at
i
c
n3 c
u
b
i
c
2n e
x
p
o
ne
n
t
i
a
l
n
! f
a
c
to
r
i
al
Page 7
DAA LAB 18CSL4
/
*
1A.
Cr
e
a
te
a
Ja
v
ac
l
as
s
ca
l
l
eS
dt
u
de
n
tw
i
th
t
he
f
ol
l
o
wi
ng
de
t
a
i
l
sa
sv
ar
i
a
bl
e
sw
it
h
in
it
.
(
i
)U
SN
(
i
i
)Na
m
e
(
i
i
i
)Br
a
nc
h
(
i
v
)Ph
o
ne
W
ri
t
ea
Ja
v
ap
r
og
r
a
mt
oc
r
ea
t
en
St
u
de
n
to
b
je
c
ts
a
n
dp
ri
n
tt
h
eU
S
N,
Na
me
,
Br
an
c
h,
a
nd
P
h
one
of
t
he
s
e
ob
j
e
ct
sw
i
t
hs
ui
t
a
bl
eh
e
ad
i
n
gs
.
*/
o
b
j
e
ct
i
ve
s
:
T
h
i
s
Pr
og
r
a
mc
o
ur
s
e
en
a
bl
e
st
ud
e
n
t
st
o
:
C
r
e
a
te
S
tu
d
e
n
to
b
j
e
ct
,
Ex
ce
p
t
i
o
n,
Bu
ff
e
r
ed
R
ea
d
e
r
i
ns
i
d
ea
cl
a
ss
*/
Method second word first letter and class name first letter of first word are of
uppercase,variable declaration with normal syntax
*/
Al
go r
ithm :
//Input: Values for USN, name, branch and phone no
//Output: Displaying the details of n student objects
//Steps:
1
)
c
la
s
s“
s
t
u
de
n
t”
i
sc
r
ea
t
e
d
2
)
D
ec
l
ar
e
va
r
i
a
bl
e
sU
SN
,
Na
me
,
Br
an
c
h
,
an
dP
h
o
n
e
no
.
3
)
af
u
nc
t
i
o
n“
re
a
d
”
i
sc
r
e
at
e
dt
h
a
ti
n
i
ti
a
l
iz
et
h
e
se
v
ar
i
a
bl
e
s
4
)
a
fu
n
ct
i
o
n“
d
is
p
l
a
y”
i
s
cr
e
at
e
d
th
a
t
pr
i
n
t
st
he
s
e
d
et
a
i
l
sl
i
k
eu
sn
,
n
ame
,
b
ra
nch andphone no
5
)
mu
l
t
ip
l
eo
b
je
c
t
so
f
“
st
u
d
en
t
”c
l
a
ss
ca
l
l
st
h
ef
u
n
ct
i
o
n“
di
s
pl
a
y”
to printthe details contained in student class.
Page 8
DAA LAB 18CSL4
P
r
o
g
ra
m
:
Import
java.util.Scanner;
public class student
{ String USN;
String Name;
String
branch;int
phone;
Void insertRecord (String reg,String name, String brnch, int ph)
{
USN=reg;
Name=nam
e;
branch=brnc
h;phone=ph;
}
Void displayRecord()
{
System.out.println(USN+" "+Name+" "+branch+" "+phone);
}
Public static void main(String
args[]){ student s[]=new student
[100]; Scannersc=new
Scanner(System.in);
System.out.println("enter the number of students");
int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=new
student();
for(int j=0;j<n;j++)
{
Page 9
DAA LAB 18CSL4
System.out.println("enter the USN,Name,branch,phone");
String USN=sc.next();
String
Name=sc.next();
String
branch=sc.next();int
phone=sc.nextInt();
Page
DAA LAB 18CSL4
s[j].insertRecord(USN,Name,branch,phone);
}
for(int
m=0;m<n;m++){s[m]
.displayRecord();
}
}
}
O
U
T
P
U
T
V
i
v
aQ
ue
s
t
i
o
ns
:
-
1. Define Class ?
2. What is array of object?
3 How to create object ?
Page
DAA LAB 18CSL4
/
*
1
b.
Wr
i
t
ea
Ja
v
a
pr
o
g
ra
mt
o
i
mp
l
em
e
nt
t
h
eS
t
ac
k
us
i
n
ga
rr
a
y
s.
Wr
i
t
eP
us
h
(
)
,
Po
p(
)
a
n
d
Di
s
pl
a
y(
)
me
t
h
od
s
t
od
em
o
ns
t
ra
t
e
i
ts
w
or
k
i
ng
.
*
/
o
b
j
e
ct
i
ve
s
:
This Program enable students to :
Learn the techniques of stacks and queues to solve problems.
A
l
g
orithm :
// Input : Elements to be pushed or popped from the Stack
// Output : pushed elements, popped elements, contents of stack
Steps:
1
)
A cla sscrea t
e da nd vari
ab l
e s ar e
d
e
f
i
ne
dl
i
k
ema
x
,
ar
r
[]
,
t
op
2
)
A cu stom i
z ed co nst
ru ct
o ro fs a m
e
c
l
as
si
s
us
ed
f
or
i
ni
t
i
al
i
zi
n
g
size,topvariables and the array[]
3
)
A fun cti
on push() i
s created f
o r p
u
s
h
in
gt
h
ee
l
em
e
nt
si
n
to
st
a
ck
4
)
Afun cti
on p op() i
s cr
e ated for p op
p
i
n
gt
he
e
l
eme
n
t
sf
r
oms
ta
c
k
5
)
Afunction d isplay() i
s
cr
ea
t
e
df
o
rd
i
s
pl
a
yi
n
gt
he
e
l
e
me
nt
s
i
nt
he
st
a
c
k:
6
)
A boolen fu n c
ti
o n i
s
cr
ea
t
e
dt
o
ch
e
ck wh
e
t
h
er
s
ta
c
ki
s
empty or full:Boolen
Page
DAA LAB 18CSL4
P
r
o
g
ra
m
:
import java.util.Scanner;
{
int q=1;
Scanner sc=new
Scanner(System.in);while(q!=0){
System.out.println("enter 1. push 2.pop 3.
display ");System.out.println("enter your
choice");
intch=sc.nextInt()
;switch(ch)
{
case 1:System.out.println("enter the element to be
pushed");int ele=sc.nextInt();
m.push(ele)
;break;
case 2: int popele;
popele=m.pop();
System.out.println("the poped element is");
System.out.println(popele+" ");
break;
case 3:System.out.println("elements in the stack are");
m.display();
break;
case 4:q=0;
}
}
}
Page
DAA LAB 18CSL4
Output:
20
10
enter 1. Push 2.pop
3.displayenter your choice
1
enter the element to be
pushed30
enter 1. Push 2.pop
3.displayenter your choice
1
enter the element to be
pushed40
enter 1. Push 2.pop 3. Display
Page
DAA LAB 18CSL4
enter your choice
3
elements in the
stack
40
30
20
10
O ut
c om es:
On completion of this Program, the students are able to :Apply techniques of
stacksand queues to solve problems.
V
i
v
aQ
ue
s
t
i
o
ns
:
1
.W
ha
t
i
ss
t
ac
k
?
2
.
Di
ff
e
r
en
c
eb
e
t
w
e
en
st
a
c
k&
qu
e
u
e
?
3
.
Wha
t
a
r
em
aj
o
ro
pe
r
a
t
i
on
i
ns
t
ac
k
?
4
.W
ha
t
i
sa
r
r
ay
?
Page
DAA LAB 18CSL4
/
*
2
A.
D
es
i
gn
as
up
e
rc
l
as
sc
a
l
le
dS
t
a
f
fw
it
hd
e
t
ai
l
sa
sS
t
a
ff
I
d
,N
a
me
,
Ph
on
e
,S
a
l
ar
y
.
E
x
t
e
nd
t
hi
sc
l
as
s
by
wr
i
t
i
ng
th
r
ee
su
b
c
l
as
se
sn
a
me
l
yT
ea
c
h
in
g(
d
om
a
i
n,
p
u
b
l
ic
a
t
io
nT
s
)
,e
c
hn
i
c
al
(
sk
i
ll
s
)
,a
nC
o
n
dt
r
ac
t(
p
e
ri
o
d)
.
Wr
i
t
ea
Ja
v
ap
r
og
r
amt
o
r
ea
d
a
n
d
di
s
pl
a
ya
t
le
a
ss
t
3t
a
f
fob
j
e
ct
so
f
a
ll
t
hr
e
ec
a
t
eg
or
i
es
.
*
/
O
b
j
e
ct
i
ve
s
:
This Program enable students
to :Learn the inheritance
A
l
g
or
i
t
hm
:
//Input: StaffId, Name, Phone and Salary
1
)
A clas s cre
ated na m ed“
sta f
f”.
2
)
Va ri
ab lesar
ed ecl
a red i
nthec l
as slike S t
affId,
N am e,
P ho neNo ,
S
al
ary.3) Constructor is used to initialize thevalues of these
variables.
4
)
F
un cti
o niscr
e at
e dt
o re adval
u es fr
o m co nsoleofthevari
ables: readValues()
System.out.println(“enter staff
id”);StafId= (s1.next());
System.out.println(“enter
name”); name= (s1.next());
System.out.println(“enter
phone”); phone= (s1.next());
System.out.println(“enter
salary”); salary= (s1.nextInt());
}
5
)
Su bclass “teaching” i
s created tha ti
nher
it
s superc lass“staff”.
6
)
Tw o fun cti
o nsare defi
ned inside “teac
hing
” cl
a ss.T hey are “dom ai
n”
and
“publications”.Thesefunctionsprintthedomainofparticularstaffandno.
of publications by himrespectively.
7
)
Ac
la
s
si
s
cr
ea
t
e
d“
t
e
ch
n
i
ca
l
”
th
a
ti
n
he
r
it
s
su
p
er
c
l
as
s
“
st
af
f
”
.
8
)
On
ef
u
n
ct
i
on
i
sd
e
f
i
ne
d
un
d
e
r“
t
e
ch
n
ic
a
l
”c
l
as
s
na
m
ed
“
s
ki
l
l
s”
.
T
hi
s
f
un
Page
DAA LAB 18CSL4
ctions displays the skills of particularstaff.
Page
DAA LAB 18CSL4
9
)
Ac
la
s
s
i
sc
r
e
at
e
dn
a
me
d
“
c
on
t
r
a
ct
”
t
ha
t
in
h
e
r
it
s
t
he
su
p
e
r
cl
a
ss
“
st
a
f
f
”
1
0
)
On efunc t
ion i
s defi
nedun der“contrac t”c
l
a ssn ame d “
pe ri
od ”.
T h
i
s
f
u
nction displayed the contract period of the particularstaff.
1
1
)
From the
mainmethod,objectsaremadeofeachsubclassandfunctionsarecalled.
Public static void main(Stringargs[])
Technical t2=new
Technical();
t2.readValue(); t2.skills();
Contract c1=new
Contract();
c1.readValue();
c1.period();
}
Page
DAA LAB 18CSL4
P
r
o
g
ra
m
:
class
Staff{ intstaffid,phon
e,salary;String name;
public Staff(int id , int no, intsal, String na)
{ staffid=id;
phone=no;
salary=sal;
name=na;
}
void display()
{
System.out.println(" ");
System.out.println("Staff ID:"+ " "+ staffid);
System.out.println("Staff Phone number:" + " "+ phone);
System.out.println("Staff Salary:" +" "+ salary);
System.out.println("Staff Name:" +" "+ name);
}
}
class Teaching extends Staff
{ String domain;
int
no_of_publication
s;
public Teaching(int id, int no, intsal, String na,Stringd,intnop)
{ super(id,no,sal,na);
domain=d;
no_of_publications=no
p;
}
voidTdisplay()
Page
DAA LAB 18CSL4
{
System.out.println(" ");
Page
DAA LAB 18CSL4
System.out.println("Teaching Staff
Details");super.display();
System.out.println("Domain :" +" "+domain);
System.out.println("No_of_publications:"+"
"+no_of_publications);
}
}
class Technical extends Staff
{ String skills;
public Technical(int id , int no, intsal, String
na,Stringsk){ super(id,no,sal,na);skills=sk;
}
voidTedisplay(){
System.out.println(" ");
System.out.println("Technical Staff Details");
super.display();
System.out.println("Skills :" + " "+skills);
}
}
Page
DAA LAB 18CSL4
Teaching t1=new Teaching(11,998765434,31000,"Anil","CSE",10);
Teachingt2=new Teaching(12,996655546,30000,"Anu","ISE",9);
Teachingt3=newTeaching(13,999933442,32000,"Anusha","EEE
",8);t1.Tdisplay();
t2.Tdisplay()
;
t3.Tdisplay()
;
Technicalte1=new
Technical(21,994433221,22000,"Kumar","C");
Technicalte2=new
Technical(22,998877665,28000,"Krisna","Java");Technical
te3=new Technical(23,991654321,33000,"Kiran","Java");
te1.Tedisplay();
te2.Tedisplay()
;
te3.Tedisplay();
Contract ct1=new Contract(31,998765434,35000,"Anil",3);
Contract ct2=new
Contract(32,912345678,39000,"Meghana",2);Contract
ct3=new Contract(33,992233445,30000,"Uma",4);
ct1.Cdisplay();
ct2.Cdisplay()
;
ct3.Cdisplay()
;
}
}
O
u
t
p
u
t:
-- -- -- -- -- -- -- -- ---
Page
DAA LAB 18CSL4
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 11
Staff Phone number: 998765434
StaffSalary: 31000
Staff Name: Anil Domain
:CSE
No_of_publications:10
Page
DAA LAB 18CSL4
-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 12
Staff Phone number: 996655546
StaffSalary: 30000
Staff Name:
AnuDomain :ISE
No_of_publications: 9
-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 13
Staff Phone number: 999933442
StaffSalary: 32000
Staff Name:
AnushaDomain :EEE
No_of_publications: 8
-- -- -- -- -- -- -- -- ---
Technical Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 21
Staff Phone number: 994433221
StaffSalary: 22000
Staff Name:
KumarSkills : C
-- -- -- -- -- -- -- -- ---
Page
DAA LAB 18CSL4
Technical Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 22
Staff Phone number: 998877665
StaffSalary: 28000
Staff Name: Krisna Skills
: Java
-- -- -- -- -- -- -- -- ---
Technical Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 23
Staff Phone number: 991654321
StaffSalary: 33000
Staff Name: Kiran Skills
: Java
-- -- -- -- -- -- -- -- ---
Contract Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 31
Staff Phone number: 998765434
StaffSalary: 35000
Staff Name: Anil
Page
DAA LAB 18CSL4
Contract Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 33
Staff Phone number: 992233445
StaffSalary: 30000
Staff Name: Uma
ContractPeriod: 4years
O
u
t
c
o
me
s:
On completion of this Program, the students are able to :
• Apply inheritance concept to solve theproblem.
V
i
v
aQ
ue
s
t
i
o
ns
:
1
.D
ef
i
n
es
up
e
r
c
l
a
ss
?
2
.D
ef
i
n
es
ub
c
l
a
ss
e
s?
3
.
Def
i
n
ei
nh
e
r
it
a
n
ce
?
4
.H
ow
t
o
cr
e
a
te
o
bj
e
ct
f
or
s
up
e
r
cl
a
ss
e
s?
5
.H
ow
t
o
us
e
fu
n
c
t
i
on
f
r
om
i
n
he
r
it
e
dc
l
a
ss
?
Page
DAA LAB 18CSL4
/* 2B. Write a Java class calledCustomer 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 “/”.
*/
//Output: name and date of birth displayed in <name, dd, mm, yyy>
formatSteps:
1
)
Ac
l
as
s
na
m
e
d“
c
u
st
o
me
r
”i
s
cr
ea
t
e
d
.
2
)
Va
r
i
ab
l
e
sa
re
d
ef
i
n
ed
as
n
a
me
a
n
dd
a
t
e
_
of
_
b
ir
t
h
3
)
Va
l
ue
s
ar
e
re
a
d
fr
o
mt
h
eu
s
e
r
ofnameanddateofbirthindd/mm/yyyformatasstrings. Scanner sc =
new Scanner(System.in );
String name=sc.next();
while (strToken.hasMoreElements())
System.out.println(name+strToken.nextElement());
}
6
)
Th
eo
u
t
p
u
ti
s
di
s
pl
a
ye
dt
h
e
ni
nt
h
ef
o
r
mo
f
<n
a
m
e
,d
d
,
mm
,y
y
y
>
Page
DAA LAB 18CSL4
P
r
o
g
ra
m
:
Import java.util.Scanner;
importjava.util.StringTokeniz
er;classcustomer
{
String name;
String date;
public void
read()
{
Scanner input =new Scanner(System.in);
name=input.next();
date=input.next();
}
public void display()
{
System.out.print(name+",
");String delims="/";
StringTokenizerst=new StringTokenizer(date,delims);
while(st.hasMoreElements()){ System.out.print(st.nextEle
ment()+",");
}
System.out.println();
}
Page
DAA LAB 18CSL4
for(int i=0;i<n;i++)
{
cus[i]=new
customer();
cus[i].read();
}
for(int i=0;i<n;i++)
cus[i].display();
}
}
Output:
Page
DAA LAB 18CSL4
V
i
v
aq
ue
s
t
i
o
ns
:
1
.D
ef
i
n
es
tr
i
n
gTo
k
e
n
i
ze
r
?
2
.W
ha
t
i
su
s
eo
f
d
el
i
mi
t
er
?
3
.D
ef
i
n
ed
at
a
t
yp
e
s?
4
.D
ef
i
n
ed
at
a
me
mb
e
r
s
us
e
in
d
i
f
fe
r
e
nt
d
at
a
t
yp
e
s?
5
.H
ow
t
o
cr
e
a
te
c
l
as
s
i
nj
a
va
?
Page
DAA LAB 18CSL4
/* 3A. Write a Java program to read two integersa andb . Computea /b and print,
whenb is notzero. Raise an exception whenb is equal to zero.*/
a
=sc.nextInt();
b
=sc.nextInt();
4
)
Th
ecode t
o calcu l
a t
edi
vision iske ptu n de r t
r
y
bl
o
c
ktry{ System.out .println(a /b );
5
)
Th e arethe m eti
cexc epti
on raisedwh enb=
0
i
s
ha
n
dl
e
di
n
ca
t
ch
b
l
o
ck
t
ha
t
follows tryblock
catch(Arithmetic Exception
e){e.printStackTrace();
Page
DAA LAB 18CSL4
Program:
importjava.util.Scanner;
class division
{
public static void main(String[] args)
{
inta,b,result;
Scanner input =new Scanner(System.in );
System.out .println("Input two integers");
a=input.nextInt();b=input.nextInt();
try
{
result=a/b;
System.out .println("Result="+resu
lt);
}
catch(ArithmeticException e)
{
System.out .println("exception caught: Divide by zero error"+e);
}
O
u
t
p
u
t:
Input
twointegers62
Result=3
Input
twointegers3 0
exception caught: Divide by zero error java.lang.ArithmeticException: / by zero
Page
DAA LAB 18CSL4
Apply Exception concepts and Develop a program that can be solved to read
two integers a andb and to Compute a /b and print, when b is not zero. Raise an
exception when b is equal to zero.
V
i
v
aq
ue
s
t
i
o
ns
:
1
.W
ha
t
i
se
x
ce
p
t
i
o
n?
2
.H
ow
t
o
ha
n
dl
e
ex
ce
p
t
i
o
n?
3
.Wh
a
t
i
si
n
he
r
it
a
n
ce
?
4
.Wh
a
t
i
s
ab
es
t
c
as
e
ef
f
i
c
i
en
cy
?
Page
DAA LAB 18CSL4
A
l
gorithm :
•//Inp ut: R and om num b er
•//Out put :sq ua r
e and c ub
eo
fthe num berS t
ep s:
1
.Three t
h r eads arecreated
.
2
.Three cla sse s R andom N
u
mber, Square Ge neratorand C
u
be
G
en
e
ra
t
o
ra
r
e
c
re
a
t
ed
3
.Class Ra n dom Nu m ber
g e
n
e
ra
tesa nint
eg erus i
ngran dom
numbergenerator and prints the integer with threadt1
4
.Ne xt
c las sSq ua reGene r
a t
o
r
is
call
e dtogen eratesqu ar
eo ft
h
e
nu
mb
e
r
a
nd printit with threadt2.
5
.Atl
a stcla ssC ub eG enera t
o
r
i
sc
a l
led t
o genera t
ec ubeofthen
u
mb
er
a
nd printit with threadt3.
P
r
o
g
ra
m
:
importjava.util.*;
Page
DAA LAB 18CSL4
for(int i=0;i<5;i++)
{
num=r.nextInt(100);
System.out .println("first thread generated number is
“ +num);Thread t2=new Thread (new second(num));
t2.start();
Thread t3=new Thread(new third(num)); t3.start();
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Page
DAA LAB 18CSL4
O
U
T
P
U
T:
Page
DAA LAB 18CSL4
V
i
v
aq
ue
s
t
i
o
ns
1
.W
ha
t
a
r
et
hr
ea
d
s?
2
.W
ha
t
i
si
n
he
r
it
a
n
ce
?
3
.H
ow
t
oi
m
pl
em
e
nt
m
ul
t
i
-
th
r
ea
d
s
?
4
.
Wha
t
i
sd
i
f
fe
r
e
nc
e
b
et
w
e
en
pr
o
c
es
s
an
d
t
h
re
a
d
s?
Page
DAA LAB 18CSL4
/*4. Sort a given set of n integer elements using the Quicksort method and compute its
time complexity. Run the program for varied values ofn > 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 orcan 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.*/
Quick sort is one of the sorting algorithms working on the Divide and Conquer
principle. Quick sort works by finding an element, called pivot, in the given array and
partitions the arrayinto three sub arrays such that
The left sub array contains all elements which are less than or equal to
the pivotThe middle sub arrays contains pivot
The right sub array contains all elements which are greater than or equal to the pivot.
Quicksort is well-known sorting algorithms based on the divide and conquer technique.
Quicksortdividesitsinputelementsaccordingtotheirvalue.Specifically,itrearrang
eselem ents of agivenarrayA[0 n-1]toachieveitspartition,asituationwhereallthe
elements before some position s are smaller than or equal to A[s] and all the elements
aftersome position s are greater than or equal to A[s].We call this element the pivot.
After a partition has been achieved, A[s] will be in its final position in the sorted array, and we
cancontinue sorting the two sub arrays of the elements preceding and following A[s]
independently.
F
e
a
t
u
re
s
:
•
D
ev
e
lo
p
e
db
y
C
.
A.
R
.
Ho
ar
e
•
E
ff
i
c
ie
n
t
al
g
or
i
t
hm
•
N
OTs
t
a
b
le
s
or
t
Page
DAA LAB 18CSL4
•
S
ig
n
i
fi
c
an
t
l
yf
a
st
e
r
in
p
ra
c
t
i
c
e,
t
ha
no
t
h
e
ra
l
g
or
i
t
hm
s
A
L
G
O
R
IT
H
M
Quicksort (A [l...r ] )
// So rt s a s
u
b
ar
r
ay
b
yq
ui
c
ks
o
rt
// Inp u t : A s
u
b
ar
r
ay
Al
.
.
.
r
[]
of
A[
0
..
.
n
-1
]
,d
e
f
in
e
d
by
i
t
sl
e
ft
a
nd
ri
g
ht
ind
i
c
es
la
n
dr
//O utp u t : T h
e
s
ub
ar
r
a
yl
A
[.
.
.
r]
so
r
t
ed
i
nn
on
de
c
r
e
as
i
n
go
rd
e
ri
f
l
<r
A
L
G
O
R
IT
H
M
Partition ( A [l...r ] )
/
/
P
ar
t
i
t
i
on
sa
s
u
b
ar
r
a
yb
y
us
i
n
gi
n
tf
i
r
st
e
le
m
en
t
a
sa
p
iv
o
t
P ← A [l ]
i ←l ; j ←r + 1
repe at
repeati ← i + 1 until A [i] >= p
repeatj ← j – 1 until A [j] <= p
swap ( A [i] , A [j] )
untili > = j
Page
DAA LAB 18CSL4
PROG R A M
Import java.util.Random;
import java.util.Scanner;
if(low<high)
{
int s=partition(a,low,high);
sort(a,low,s-1);
sort(a,s+1,high);
}
}
stubint[ ] a;
intI,n;
System.out.println("Enterthearraysize");Scannersc
=new
Scanner(System.i
n);
n=sc.nextInt();
Page
DAA LAB 18CSL4
a= newint[max];
Random generator=new Random();
Page
DAA LAB 18CSL4
for( i=0;i<n;i++)
a[i]=generator.nextInt(20);
System.out.println("Array before
sorting");for( i=0;i<n;i++)
System.out.println(a[i]+" ");
Long StartTime=System.nanoTime();
quicksort m=new quicksort();
m.sort(a,0,n-1);
longstopTime=System.nanoTime();
longelapseTime=(stopTime-
startTime);
System.out.println("Time taken to sort array is:"+elapseTime+"nano seconds”);
System.out.println("Sorted array is"); for(i=0;i<n;i++) System.out.println(a[i]);
}}
Page
DAA LAB 18CSL4
O
U
T
P
U
T:
Enter the array size
6Array before sorting
17
17
12
2
10
3
Timetakentosortarrayis:16980nanosec
ondsSorted arrayis
2
3
10
12
17
17
V
ivaquesti
o ns
1. How quick sort works
2. What is the worst-case behavior (number of comparisons) for quick sort?
3. Explain Divide and conquer method. Give an example
Page
DAA LAB 18CSL4
/* 5.Sort a given set ofn integer elements using Merge Sort method and compute its
time complexity. Run the program for varied values ofn > 5000, and record the time
taken to sort. Plota graph of the time taken versusn 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 bestcase.*/
O
b
j
e
ct
i
ve
s
:
This Program enable students to :
• Learn Merge sorting and searchingtechniques.
• Get exposed to Merge Sort algorithm designtechniques.
The basic operation in merge sort is comparison and swapping. Merge sort algorithm
calls it self recursively. Merge sort divides the array into sub arrays based on the
position of the elements whereas quick sort divides the array into sub arrays based on
the value of the elements.
ALGORITHM
Mergesort(A[0...n-1])
//S orts a rray A
[
0
.
..
n
-
1]
by
r
ec
ur
s
i
v
eme
r
ge
s
or
t
.
/
/In put a n arr a
y
A
[
0.
.
.n
-
1]
o
fo
r
de
r
ab
l
ee
l
em
en
t
s
.
//O u t
p u t Arra y
A
[
0.
.
.
n-
1
]s
o
rt
e
di
n
no
n-
d
ec
r
ea
s
i
n
go
rd
e
r
.
I
f
n>
1
Copy A[0...(n/2)-1] to B[0...(n/2)-1]
Copy A[(n/2)...n-1], to C[0...(n/2)-1]
Mergesort(B[0...(n/2)-1])
Mergesort(C[0...(n/2)-
1])Merge(B,C,A)
Page
DAA LAB 18CSL4
ALGORITHM
Merge(B[0...p-1],C[0...q-1],A[0...p+q-1])
//M e rge s tw o s o rt
ed ar ra
y
s
in
t
oo
n
es
or
t
ed
ar
r
ay
//In put : Arra ys B [0..
.p-1 ]a
n
dC
[
0.
.
.
q-
1
]b
o
th
so
r
te
d
// Ou tpu t :S o r
te d a r
ray A [0
.
.
.
p+
q
-1
]
of
t
he
el
e
me
nt
s
of
B
an
d
C
i←0;j←0;k←0;
T
i
m
eCom p l
e xi
t y
C (n) € Θ (nlogn)
Mergesortworksbydividingthegivenarrayintotwosubarraysofequalsize
The sorted sub array are then merged to get the solution for the originalarray
The principal shortcoming of mergesort is the linear amount of extra storage the
algorithmrequired.
Page
DAA LAB 18CSL4
Program :
importjava.util.Rando
m;
importjava.util.Scanner;
public classMergeSort2
{
static final int MAX = 10005;
static int[] a = new int[MAX];
b[i++] = a[j++];
if (h > mid)
for (k = j; k <= high; k++)
b[i++] = a[k];
else
for (k = h; k <= mid; k++)
b[i++] = a[k];
Page
DAA LAB 18CSL4
OU TP UT 1:
Enter Max array size: 6
-- -- -- -- -- --
Time Complexity (ms) for n = 6 is :0.307211
V
i
v
a
1
What isMergesort
2
Explain Decrease/transfer and conquer method. Give
DifferencebetweenDivideandconquerme
3 andDecrease/transferandconquerm
4
Sort the given elements using Mergesort 67 24 9 5 25 66
Page
DAA LAB 18CSL4
6A). Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method
Learn the 0/1 Knapsack problem using Dynamic Programming method to implement in
Wearegivenasetofn itemsfromwhichwearetoselectsomenumberofitemstobecarried
inaknapsack(BAG).Eachitemhasbothaweight andaprofit .The objectiveistochoosethe set
of itemsthat fits in the knapsack and maximizes theprofit.
Given a knapsack with maximum capacityW , and a setS consisting ofn items , Each itemi
has some weightwi and benefit valuebi (allwi , bi andW are integer values)
Problem: How to pack the knapsack to achieve maximum total value of packed
items?
Itgivesusawaytodesigncustomalgorithmswhichsystematicallysearchallpossibilities
(thusguaranteeingcorrectness)whilestoringresultstoavoidrecomputing(thusprovidin
g efficiency).
A LG OR IT H M
//Input: (n items, W weight of sack) Input: n, wi,,, vi and W – all integers
//Output: V(n,W)
Steps:
elementsRepeat for i = 0 to n
set V(i,0) = 0
Repeat for j = 0 toW
Set V(0,j) =0
//complete remaining entries
PrintV(n,W)
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
importjava.util.Scanne
r; public class
KnapsackDP
{
static finalintMAX=20;//max.no.ofobjects static
intw[]; // weights 0 ton-1
staticintp[]; // profits 0 ton-1
staticintn; // no.
ofobjects
staticintM; // capacity of Knapsack
staticintV[][]; // DP solution process-
table staticint Keep[][]; // to get objects in
optimal solution
Page
DAA LAB 18CSL4
V[i][j] = V[i - 1][j];
Keep[i][j] =0;
//FindtheobjectsincludedintheKnapsack r
=M;
System.out.println("Items = ");
for (int i = n; i > 0; i--) // start from Keep[n,M]
if
(Keep[i][r] == 1)
{ System.out.println(i +
"");r = r -w[i];
}
System.out.println
();return V[n][M];
}
Page
DAA LAB 18CSL4
O
U
T
P
U
T1
:
4
Enter number of objects:
3
Enter Weights:
2
1
1
Enter Profits:
4
5
2
Items
=3
2
1
Optimal solution = 11
BUILD SUCCESSFUL (total time: 35 seconds)
Solve0/1KnapsackproblemusingDynamicProgrammingmethodtoimplementinjava
V
i
v
aq
ue
s
t
i
o
ns
1
.W
ha t
is dynam i
cp r
og r
a m?
2
.K
napsack probl
em can be
s
o
l
ve
d
by
us
i
ng
wh
i
c
hm
et
h
o
d.
3
.W
ha t
i
sthed i
ff
erencebetw e
e
n
d
y
na
mi
c
me
th
o
d
an
d
g
re
ed
y
me
t
h
od
pr
o
graming Techniques ?
Page
DAA LAB 18CSL4
/*6B. Implement in Java, the 0/1 Knapsack problem using Greedy method.*/
Learn the 0/1 Knapsack problem using Greedy method to implement in java
A
L
G
O
R
IT
H
M
:
K
n
a
p
s
ac
k
(
i
,
j)
//Input: A nonnegative integer i indicating the number of the first items being considered and a
nonnegative integer j indicating the Knapsack’s capacity.
//Note: Uses as global variables input arrays Weights [1...n ], Values [ 1… n ] and
tableV [0…n, 0…W ] whose entries are initialized with -1’s except for row 0
and column 0 initialized with 0’s.
if V [i, j] < 0
if j< Weights[i]
thenvalue = Knapsack ( i-
1, j )
else
value = max ( Knapsack ( i -1, j ),
values[I] + Knapsack ( i-1, j-Weights[i] ) )
V[i j] = value
return V [ i, j ]
Page
DAA LAB 18CSL4
E
f
f
i
c
ie
n
cy
:
• RunningtimeofKnapsackproblemusingdynamicprogrammingalgorithmi
s:
O(n * W)
• Timeneeded tofindthecompositionofanoptimalsolutionis:O(n+W)
importjava.util.Scanner;
Consider a matrix of different weights (starting from zero total weight ) and different
capacity(starting from zero to given knapsack capacity) indicating the profit value.
also zero.
When knapsack capacity is less than weight then profit is the previous
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
importjava.util.Scanner;
classKObject{ // Knapsack objectdetails
floatw;
float p;
float r;
}
public class KnapsackGreedy {
static final intMAX=20; // max. no. of
objects staticintn; // no. of
objects
staticfloatM; // capacity ofKnapsack
ReadObjects(obj)
;Knapsack(obj);
scanner.close();
}
System.out.println("Enter Profits:
");for (int i = 0; i < n; i++)
obj[i].p = scanner.nextFloat();
Page
DAA LAB 18CSL4
// sort objects in descending order, based on
p/w ratiofor(int i = 0; i<n-1; i++)
scanner.close
();
}
}
}
System.out.println("i = " + i);
if (i < n)
x[i] = U / kobj[i].w;
totalprofit = totalprofit + (x[i] * kobj[i].p);
System.out.println("The Solution vector, x[]:
");for (i = 0; i < n; i++)
System.out.print(x[i] + " ");
System.out.println("\nTotal profit is = " +
totalprofit);
}
Page
DAA LAB 18CSL4
Page
DAA LAB 18CSL4
O
U
T
P
U
T:
V
i
v
aq
ue
s
t
i
o
ns
:
1. W hat i
s dynam i
cp r
o
g
ra
m
?
2. Knap sackp r
o bl
em c
a
nb
es
o
lv
e
d
by
us
i
ng
wh
i
c
hm
et
h
o
d.
3. W hati
sthedif
ference
b
et
w
ee
n
d
yn
a
mi
c
me
th
o
d
an
d
g
re
ed
y
me
t
h
od
pr
o
graming Techniques?
Page
DAA LAB 18CSL4
* 7.Fromagivenvertexinaweightedconnectedgraph,findshortestpathstoothervertices using
Dijkstra's algorithm. Write the program inJava.*/
Dijkstra’s algorithm finds shortest paths to a graph’s vertices in order of their distance
from a given source. First, it finds the shortest path from the source to a vertex nearest to
it, then to a second nearest and so on.
d d d
Page
DAA LAB 18CSL4
A
i
m
:
A l
g orit
h m :
// Input: A weighted connected graph G ={V,E}, source s
•R
e
ad
w
e
i
gh
t
e
dg
r
a
ph
G
•P
r
i
nt
w
ei
g
ht
e
dg
r
a
ph
•I
n i
ti
ali
zed i
s t
a ncefr o m sou r
ceforallvert
i
c
es
a
sw
e
i
g
ht
b
et
w
e
en
s
ou
r
c
e
no
d
e
andother vertices, i, and none intree
// initial condition
•F
o
ra
l
l
o
th
er
v
e
r
ti
c
es
,
dv
[
i
]=
w
t
_g
r
a
p
h[
s
,
i
],
T
V[
i
]=
0
,
pr
e
v[
i
]
=0
d
v[
s
]
=0
,
pr
e
v[
s
]
=s
/
/
sourcevertex
•R
e
pe
a
t
f
o
ry
=1
t
o
n
{ minm = dv [k]
j=k
Page
DAA LAB 18CSL4
P RO G RA M
importjava.util.Scann
er;public class Dijkstra
{
int d[ ]=new int[10];
int p[ ]=new int[10];
int visited[ ]=new int[10];
Page
DAA LAB 18CSL4
}
Page
DAA LAB 18CSL4
}
void path(intv,int s)
{
if(p[v]!=-1)
path(p[v],s);
if(v!=s)
System.out.print("->"+v+" ");
}
void display(ints,intn)
{ int i;for(i=0;i<n;i++)
{
if(i!=s){ System.out.print(
s+" ");
path(i,s);
if(i!=s)
System.out.print("="+d[i]+" ");
System.out.println();
}
}
public static void main(String[]
inti,j,n,s;
System.out.println("enter the number of
vertices");Scanner sc = new Scanner(System.in);
n=sc.nextInt();
System.out.println("enter the weighted matrix");
for(i=0;i<n;i++)
Page
DAA LAB 18CSL4
for(j=0;j<n;j++)
a[i][j]=sc.nextInt();
System.out.println("enter the source vertex");
s=sc.nextInt();
Dijkstratr=new
Dijkstra();tr.dijk(a,s,n);
System.out.println("the shortest path between source"+s+"to remaining vertices are");
tr.display(s,n);
sc.close();
}}
Output:
0 ->1 =3
0 ->1 ->2=7
0 ->1 ->3=5
0 ->1 ->3 ->4 =9
Page
DAA LAB 18CSL4
V
i
v
aq
ue
s
t
i
o
ns
H
o
1
.wd
o
y
o
ur
e
p
re
s
e
nt
t
he
g
r
ap
h
?
A
2
.p
pl
i
c
at
i
on
o
fD
i
j
k
st
r
as
A
l
g
or
i
t
hm
.
D
3
.i
f
f
er
e
nc
e
be
t
w
e
en
Fl
o
yd
sa
n
d
Di
j
k
st
r
as
a
l
g
or
i
t
hm
.
D
4
.i
j
k
st
r
as
a
l
go
r
i
t
hm
ca
n
b
es
o
l
v
ed
by
u
s
i
ng
w
hi
c
ht
y
pe
a
l
go
r
i
t
hm
me
t
h
o
d.
Page
DAA LAB 18CSL4
The algorithm begins by sorting the graph’s edges in increasing order of their weights.
Then starting with the empty sub graph, it scans this sorted list adding the next edge on
the list to the current sub graph if such an inclusion does not create a cycle and simply
skipping the edge otherwise.
When you select a minimum weight path, it will have source and destination vertices.
These
twoverticesshouldnothavesameancestororparent.Ifboththeverticeshavethesameorigin,
then it isa cyclicgraph.
D
C
B
A
Here CD is the current edge. Vertex C is the parent of D. But C has parent vertex called
B. For B also a parent called A. According to kruskal’s algorithm, We should add all
previous path to the current path.Then here vertex A becomes the parent of vertex D.
Page
DAA LAB 18CSL4
A
i
m
:
Kruskal's Algorithm for computing the minimum spanning tree is directly based on the
generic MST algorithm. It builds the MST in forest. Prim's algorithm is based on a generic
MST algorithm.It uses greedy approach.
A
l
g
or
i
t
hm
:
K
r
u
s
ka
l
'
sA
lg
o
r
i
t
hm
Start with an empty set A, and select at every stage the shortest edge that has not been
chosen orrejected, regardless of where this edge is situated in graph.
•I
n
i
ti
a
l
ly
,
ea
ch
v
e
r
t
ex
i
s
in
i
ts
o
wn
t
r
e
ei
n
f
or
es
t
.
•T
he
n
,
al
g
or
i
t
hm
co
n
s
i
d
er
ea
c
h
ed
g
e
i
nt
u
r
n,
or
de
r
b
yi
n
cr
e
as
i
n
gw
ei
g
ht
.
•I
f
an
e
du
v
g
e
(
,
)c
on
n
e
c
t
st
w
od
i
f
f
er
e
nt
t
r
e
es
,
t
he
nu
v
(
,
)i
s
ad
d
ed
t
o
t
he
s
et
o
fedgesof
theMST,andtwotreesconnectedbyanedge(u v, )aremergedintoasingl
etree.
•O
nt
h
e
ot
h
er
h
a
nd
,
i
f
an
eu
v
d
g
e
(
,)
c
on
n
e
ct
s
t
wo
v
er
t
i
c
es
i
nt
h
e
sa
me
t
r
e
e,
t
he
nu
e
d
g
e
(,
v ) is discarded.
Page
DAA LAB 18CSL4
P RO G R A M
importjava.util.Scann
er;public class
kruskal {
int parent[]=new
int[10];int find(int m)
{
int p=m;
while(parent[p]!=0)
p=parent[p];
return p;
}
void union(inti,int j)
{
if(i<j)
parent[i]=j;
else
parent[j]=i;
}
voidkrkl(int[][]a, int n)
{
int u=0,v=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]<min&&i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
Page61
DAA LAB 18CSL4
union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]);
sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=99;
}
}
}
Output:
Enter the number of vertices of the graph
6Enter the wieghted matrix
0 3 99 99 6 5
3 0 1 99 994
99 1 0 6 994
99 99 6 0 85
6 99 99 8 02
544520
(2,3)=1
(5,6)=2
(1,2)=3
(2,6)=4
(4,6)=5
The cost of minimum spanning tree = 15
Page
DAA LAB 18CSL4
V
i
v
aq
ue
s
t
i
o
ns
1
Wh
i
c
ha
re
th
e
d
at
a
st
r
u
ct
u
re
si
s
us
ed
to
re
p
r
e
s
en
t
th
e
g
r
ap
h
.
2
Wh
a
t
is
tr
e
e?
3
Wh
a
t
is
sp
an
n
i
n
gt
r
ee
?
4
Wh
a
ti
s
MST
(
M
in
i
mu
m-
c
o
st
Sp
an
ni
n
gT
r
ee
)
?
5
D
if
f
e
r
en
c
eb
e
t
w
e
en
Gr
e
e
dy
a
l
go
r
i
t
hm
an
d
D
y
na
m
i
c
al
g
or
i
t
hm
me
t
h
o
d.
Page
DAA LAB 18CSL4
9 .FindMinimumCostSpanningTreeofagivenundirectedgraphusingPrim'salgo
rithm.Implement the program in Javalanguage.
•P
r
im
'
s
al
go
r
i
t
hm
ha
s
t
h
e
pr
o
pe
r
t
y
th
a
t
t
he
e
d
ge
s
i
n
t
he
se
t
A
a
lw
a
ys
f
o
r
ma
s
i
ng
l
e
tr
e
e.
•W
eb
e
g
i
n
withsomevertexv inagivengraphG=(V,E),definingtheinitialsetof
verticesA.
•I
n
ea
c
hi
t
e
ra
t
io
n
,
w
ech
o
o
s
e
am
i
n
i
mum
-
w
ei
g
ht
e
du
g
e
(v
,
),
c
on
ne
c
t
i
n
ga
vertexvintheset Ato the vertex u outside of setA.
•T
he
v
e
r
t
eu
x
i
s
br
o
ug
h
t
i
nt
o
A
.T
h
i
sp
r
o
ce
s
s
i
sr
e
p
ea
t
e
du
n
t
i
la
s
p
an
n
i
n
gt
r
ee
i
s
f
or
me
d
.
•L
i
ke
K
r
us
k
a
l
'
sa
l
go
r
i
t
hm
,
he
r
et
o
o
,t
h
e
im
p
or
t
a
nt
f
a
ct
a
b
ou
t
MS
T
s
i
sw
e
al
w
ay
sc
h
oose thesmallest-weight edge joining a vertex inside set A tothe one
outside the set A.
•T
h
ei
m
pl
i
ca
t
i
on
o
f
th
i
s
f
ac
ti
s
t
ha
ti
t
a
dd
so
n
l
y
ed
g
es
t
h
a
ta
r
e
sa
f
e
f
or
A;thereforewhen thealgorithm terminates, the edges in set A form aMST
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
Page65
DAA LAB 18CSL4
sum=sum+min; k++;
System.out.println(u+"
->"+v+"="+min);
}
for(i=1;i<=n;i++)
if(sol[i]==0) flag=1;
if(flag==1)
System.out.println("No spanning tree");
Else
System.out.println("The cost of minimum spanning tree is"+sum);
sc.close();
}
}
Output:
Enter the number of
vertices 6Enter the
weighted graph 0
3 99 99 6 5
3 0 1 99 994
99 1 0 6 994
99 99 6 0 85
6 99 99 8 02
544520
Enter the source
vertex11->2=3
2->3=1
2->6=4
6->5=2
6->4=5
The cost of minimum spanning tree is15
Page
DAA LAB 18CSL4
V
i
v
aq
ue
s
t
i
o
ns
Page
DAA LAB 18CSL4
/
*
1
0
A.
Wr
i
t
eJ
av
a
p
ro
g
ra
m
s
to
i
mp
l
em
e
nt
A
l
l-
P
ai
r
sS
ho
r
t
e
st
P
at
h
sp
r
o
bl
e
m
u
s
i
n
gF
l
oy
d
'
sa
l
go
r
i
t
hm
.
*/
Floydsalgorithmisaclassicexamplefortheapplication
ofdynamicprogramming.Itisusedto compute the shortest distance between every two
pair of nodes ina given graph and hence it isalso called “all-pair shortest
path”algorithm
T
h
e
f
o
ll
o
wi
n
gf
or
m
ul
a
ca
nb
e
u
s
ed
t
o
f
in
d
th
e
e
a
ch
e
l
e
me
nt
i
n
th
ed
i
s
t
an
ce
m
a
t
ri
x
.
(0)
d (k) min{d (k-1)ij, d (k-1) +ik d (k-1 ) kj}
ij
where k>=1,d w
ij ij
A
L
G
O
R
IT
H
M
A
l
g
or
i
t
hm
Fl
o
yd
(
W[
1
.
.n
,
1.
.
n
])
//ImplementsFloyd’salgorithm
lengthD(0)w
fork1 to n do
fori1 to n do
forj1 to n do
D min{d(k-1)[i,j], d(k-1)[i,k]+d(k-1)[k,j]}
(k)
ReturnD(n)
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
importjava.util.Scann
er;public class floyd {
voidflyd(int [ ] [ ] w,int n)
{
inti,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=Math.min(w[i][j], w[i][k]+w[k][j]);
}
Page
DAA LAB 18CSL4
Output:
enter the number of vertices
4Enter the weighted matrix
0 99 399
2 0 9999
99 7 0 1
6 99 99 0
The shortest path
matrix is0 10 3 4
2 0 56
7 7 01
6 16 9 0
Outcomes:OnCompletionoftheseProgramenablestudentsto:
V
i
v
aq
ue
s
t
i
o
ns
Page
DAA LAB 18CSL4
10 B.
W ri
teJ avap rogram st
o i
m plem en t
T r
a ve lli
n
gS
al
e
sP
er
s
o
np
r
ob
l
e
mu
si
n
gD
yn
a
m i
c pro gram m i
n g.*
/
Objectives: This Program enable students to :
A
i
m
:
Travelling Sales Person problem: Given a set of cities and distance between every pair
of cities,the problem is to find the shortest possible route that visits every city exactly
once and returns to the starting point. Here we know that Hamiltonian Tour exists
(because the graph is complete) and in fact many such tours exist, the problem is to find
a minimum weight Hamiltonian Cycle.
For example, consider the graph shown in above figure. A TSP tour in the graph is 1 -2-
4-3-1.The cost of the tour is 10+25+30+15 which is 80.
S
o
l
u
t
io
nu
s
i
n
gD
yn
a
m
i
cP
r
og
r
a
mm
i
ng
:
Letthegivensetofverticesbe{1,2,3,4,….n}.Letusconsider1asstartingandendingpoint
ofoutput.Foreveryothervertexi(otherthan1),wefindtheminimumcostpathwith1asthe
startingpoint,iastheendingpointandallverticesappearingexactlyonce.Letthe costofthis
pathbecost(i),thecostofcorrespondingCyclewouldbe cost(i)+dist(i,1)wheredist(i,1)is the
distancefrom i to 1. Finally, we return the minimum of all [cost(i) + dist(i, 1)] values. To
calculate cost(i) using Dynamic Programming, we need to have some recursive
relation in terms of sub- problems. Let us define a termC(S, i) be the cost of the
minimum cost path visiting each vertex in set S exactly once, starting at 1 and ending
at i . We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is
the subset, then we calculate
C(S,i)forallsubsetsSofsize3andsoon.Notethat1mustbepresentineverysubset.Ifsize
ofSis2,thenSmustbe{1, i},C(S, i)=dist(1,i)ElseifsizeofS isgreaterthan2.
Page
DAA LAB 18CSL4
PRO GR AM
importjava.util.Scanner;
Page
DAA LAB 18CSL4
}
Page
DAA LAB 18CSL4
System.out.println(tour[0] +
"\n");scanner.close();
}
Page
DAA LAB 18CSL4
OU T PU T :
******* TSP DYNAMIC PROGRAMMING
******* Enter number of cities:
3
Enter Cost matrix:
1
2
3
4
5
6
7
8
5
Minimum Tour Cost: 15
Tour:
0 -> 1 -> 2 -> 0
V
i
v
aq
ue
s
t
i
o
ns
Page
DAA LAB 18CSL4
11. D
es
ig
na
nd
im
p
l
em
en
ti
nJ
a
v
at
o
f
i
nd
a
su
bs
e
to
fa
gi
v
en
se
t
S
={
Sl
,
S2
, ,
S
n}
on
f
po si
t
iv
ei
nt
eg
er
s
wh
o
seS
UM
is
e
q
ua
l
to
ag
i
ve
npo
s
it
i
ve
i
n
te
ge
rd
.
Fo
re
xa
mp
le
,
i
fS
={1 ,
2,
5,
6,
8}
ad
n
d=
9,
t
he
re
a
re
t
w
os
ol
u
t
io
ns
{1
,
2,
6
}a
nd
{
1,
8
}.
Di
s
pl
a
ya
su
it
a
bl
e
m e s
sa
ge
,i
f
th
eg
i
v
en
pr
ob
l
em
in
s
t
an
c
ed
o
es
n'
t
hav
e
aso
l
u
ti
o
n.
*/
A
i
m
:
AninstanceoftheSubsetSumproblemisapair(S,t),whereS={x1,x2, ,xn} is a setof
positive integers and t (the target) is a positive integer. The decision problem asks for a
subset ofS whose sum is as large as possible, but not larger than t.
•
A
lg
o
r
i
th
m
:
•a
c
ce
p
t
n
:n
o
of
i
t
e
msi
n
se
t
•a
c
ce
p
t
t
h
ei
r
va
l
ue
s
,
si
n
ki
n
cr
e
as
i
n
go
r
de
r
•a
c
ce
p
t
d
:s
u
mo
f
s
u
bs
e
td
e
s
i
r
e
d
•i
n
i
ti
a
l
iz
ex
[
i
]
=-
1f
o
ra
l
l
i
•c
h
ec
k
i
f
so
l
ut
i
o
np
os
s
i
b
l
eor
n
o
t
•
i
fp
o
ss
i
b
l
et
he
nc
al
lS
u
mO
f
S
u
b(
0
,
1,
s
umo
f
a
l
l
el
e
me
nt
s
)
•
S
um
Of
S
u
b(
s,
k,
r
)
//Values of x[ j ], 1 <= j < k, have been determined
//Node creation at level k taking place: also call for creation at level K+1 if possible
// s = sum of 1 to k-1 elements and r is sum of k to n elements
Page
DAA LAB 18CSL4
•I
f
(
s+s
[
k
]+
s[
k
+1
]
<=
d
)
thenSumOfSum(s+
s[k],k+1,r–s[k])
•I
f
(
s+
r
-
s[
k
]
>=
d)
A
N
D(
s
+
s[k+1])<=dTHEN {x[k]=0;
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
importjava.util.Scanner;
import static java.lang.Math.pow;
if(d==sum)
{
System.out.print("Subset={
");present=1;
for(j=1;j<=n;j++)
Page
DAA LAB 18CSL4
if(x[j]==1)
System.out.print(a[j]+",")
;
System.out.print("}="+d)
;System.out.println();
} }}
if(present==
0)
System.out.println("Solution does not exists");
Output:
V
i
v
aq
ue
s
t
i
o
ns
Page
DAA LAB 18CSL4
12. D es i
gn and im plem e
ntthepre se nceofH am i
l
t
on
i
an
C
yc
l
e
i
na
nu
n
d
i
r
ec
t
ed
G
r
a
ph
G
of
n verti
c es.* /
objectives: This Program enable students to :
Output:
An array path[V] that should contain the Hamiltonian Path. path[i] should represent
theith
vertexintheHamiltonianPath.ThecodeshouldalsoreturnfalseifthereisnoHamiltonian
Cyclein thegraph.
Page
DAA LAB 18CSL4
P
R
O
G
RA
M
importjava.util.*;
classHamiltoniancycle
{
privateintadj[][],x[],n;
publicHamiltoniancycle()
{
Scanner src = new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=src.nextInt();
x=new int[n]; x[0]=0;
for (int i=1;i<n; i++) x[i]=-1;
adj=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++) adj[i][j]=src.nextInt();
}
Page
DAA LAB 18CSL4
}
classHamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycleobj=new
Hamiltoniancycle();obj.getHCycle(1);
}
}
Page
DAA LAB 18CSL4
O
u
t
p
u
t:
Solution:
1265341
Solution:
1265431
Solution:
1326541
Solution:
1345621
Solution:
1435621
Solution:
1456231
V
i
v
aq
ue
s
t
i
o
ns
What is N-Queensproblem?
Difference between ‘Branch and bound’ and ‘Backtracking’algorithm.
What is the time complexity of N-queensproble
Page