0% found this document useful (0 votes)
33 views95 pages

18csl47 Lab Manual

Uploaded by

shashank kulal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views95 pages

18csl47 Lab Manual

Uploaded by

shashank kulal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY

(Effective from the academic year 2018 -


2019)SEMESTER – IV
Subject Code 18CSL47 CIE Marks 40
Number of Contact Hours/Week 0:2:2 SEE Marks 60
Total Number of Lab Contact Hours 36 Exam Hours 3 Hrs
Credits – 2
Course Learning Objectives: This course (18CSL47) will enable students to:
 Design and implement various algorithms in JAVA
 Employ various design strategies for problem solving.
 Measure and compare the performance of different algorithms.
Descriptions (if any):
 Design, develop, and implement the specified algorithms for the following problems
using Javalanguage under LINUX /Windows environment. Netbeans / Eclipse IDE tool
can be used for development and demonstration.
Programs List:
1.
a. Create a Java class calledStudent with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to createnStudent objects and print the USN, Name, Branch,
andPhoneof 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 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.

10. Write Java programs to


(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.

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.

Laboratory Outcomes: The student should be able to:


 Design algorithms using appropriate design techniques (brute-force, greedy,
dynamicprogramming, etc.)
 Implement a variety of algorithms such assorting, graph related, combinatorial, etc.,
in a highlevel language.
 Analyze and compare the performance of algorithms using language features.
 Apply and implement learned algorithm design techniques and data structuresto solve
real-worldproblems.
Conduct of Practical Examination:
 All laboratory experiments, excluding the first, are to be included for practical examination.
 Experiment distribution
 For questions having only one part: Students are allowed to pick one experiment from
the lot andare given equal opportunity.
o For questions having part A and B: Students are allowed to pick one experiment
frompart A and one experiment from part B and are given equal opportunity.
 Change of experiment is allowed only once and marks allotted for procedure part to
be madezero.
 Marks Distribution(Subjected to change in accoradance with university regulations)
e) For questions having only one part – Procedure + Execution + Viva-Voce:
15+70+15 =100 Marks
f) For questions having part A and B
i. Part A – Procedure + Execution + Viva = 4 + 21 + 5 = 30 Marks
 Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks
CONTENT
S

Sl.No. Particulars Page


No
Introduction 1
1a) Create a Java class called Student with the 7
followingdetails Given
1b) Write a Java program to implement the Stack 10
usingarrays.
2a) Design a super class calledStaff with details as Staff 15
Id,
Name, Phone, and Salary. Extend this class
2b) Write a Java class calledCustomer to store their 23
nameand date_of_birth. The date_of_birth format
3a) Write a Java program to read two integersa 27
andb . Compute a/b and print, when b is not
zero. Raise anexception whenb is equal to zero
3b) Write a Java program that implements a multi- 30
threadapplication that has three threads
4 Sort a given set ofn integer elements using Quick
Sort 34
method and compute its time complexity.
5 Sort a given set ofn integer elements using Merge 39
Sort
method and compute its time complexity.
6 Implement in Java, the 0/1 Knapsack problem 44
using (a)Dynamic Programming method (b)
Greedy method.
7 From a given vertex in a weighted connected graph, 53
find shortest paths to other vertices using Dijkstra's
algorithm. Write the program in Java.

8 Find Minimum Cost Spanning Tree of a given connect 59


undirected graph using Kruskal’s algorithm.
9 Find Minimum Cost Spanning Tree of a given
connectedundirected graph using Prim's algorithm 64
10 Write Java programs to
(
a) I
m p l
e me nt Al
l
- P
air
s Sh or
tes tP aths prob l
e
m usin
g
Floyd's algorithm. 68
(
b) I
m p l
e men t T
ra v
ell
ing Sal
es Pe rson p r
ob l
e
m
usingDynamic programming.

11 Design and implement in Java to find a subset of a 75


givenset S ={Sl,S2, ,Sn} ofn positive
12 Design and implement in Java to find all Hamiltonian 79
Cycles in a connected undirected Graph G ofn
verticesusing backtracking principle
DAA LAB 18CSL4

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.

 Ex: graph traversal problems, topological sorting etc

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

 Undirected graph: A graph in which the edges have no direction


 Directed graph(Digraph):A graph in which each edge is directed from
onevertex to another (or the same)vertex.

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

Analysis of algorithms means to investigate an algorithm’s efficiency with respect


toresources:
•R
u
n
n
i
ng
t
i
me
(
ti
m
eef
f
i
c
ie
n
cy
)
It indicates how fast an algorithm in question runs
•M
e
m
o
r
ys
p
a
c
e(
s
p
ac
e
ef
f
i
c
ie
n
cy
)
It deals with the extra space the algorithm requires

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

c2g(n)<=t(n)<=c1g(n) for all n>= n0

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

Enter the number of students


2 Enter the
usn,name,branch,phone1
Monika cse 93411
Enter the
usn,name,branch,phone12
gowda cse 9785

Students details are

1 Monika cse 93411


12 gowda cse 9785

Outcomes: On completion of this Program, the students are able to :


 Creating Student Class, object

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;

public class stack{ final


intmax=100;
int s[ ]=new int[max]; int top=-
1;void push(int ele)
{
if(top>=max-1)
System.out.println("stack
overflow");else
s[++top]=ele;
}
int pop()
{
int z=0;
if(top==-1)
System.out.println("stack underflow");
Else
z=s[top--];
return z;
}
void display()
{
if(top==-1)
System.out.println("stack empty");
els
e
{
for(int i=top;i>-1;i--)
System.out.println(s[i]+" ");

Dept of CSE,ATMECE,MYSURU Page11


DAA LAB 18CSL4
public static void main(String args[])

{
int q=1;

stack m = new stack();


System.out.println("program to perform stack operations");

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:

program to perform stack


operationsenter 1. Push 2.pop
3.display
enter your
choice1
enter the element to be
pushed10
enter 1. Push 2.pop
3.displayenter your choice
1
enter the element to be
pushed20
enter 1. Push 2.pop
3.displayenter your choice
3
Elements in the stack are

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

//Output: displaying the three staff objects of each


class.Steps:

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()

Scanner s1 new Scanner(System.in);


// Scanner class is defined in library in “java.util.Scanner” package. We
need toimport //this package in our program for successful compilation.

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[])

Teaching t1= new


Teaching();
t1.readValue();
t1.domain();
t1.publications():

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);
}
}

class Contract extends Staff{ int period;


public Contract(int id , int no, intsal, String na,intpd){ super(id,no,sal,na);
period=pd;}
voidCdisplay(){
System.out.println(" ");
System.out.println("Contract Staff Details");
super.display();
System.out.println("ContractPeriod:" + " "+period + "years");
}
}
public class Multilevel{
public static void main(String args[]){

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

Contract Period: 3years


-- -- -- -- -- -- -- -- ---
Contract Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 32
Staff Phone number: 912345678
StaffSalary: 39000
Staff Name: Meghana
ContractPeriod: 2years-----

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 “/”.
*/

Objectives: This program enable students to :


 Learnhowtostoretheirnameanddate_of_birthinsideJavaclasscalledCustomer.

//input: name and dtae_of_birh in dd/mm/yyy format

//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 );

System.out .println("enter name");

String name=sc.next();

System.out .println("enter date of birth in dd/mm/yyy format");

String date = sc.next();


4
)
Ao
b
je
c
t
i
s
cr
e
at
e
d
of
S
t
ri
n
gT
ok
e
n
i
z
er
c
l
as
s
a
nd
i
s
us
e
df
o
r
ca
l
l
i
ng
t
he
m
e
t
ho
d
o
f
t
hi
s
cl
a
ss
.
5
)
Th
e
me
t
h
o
d“
h
as
m
o
re
e
l
e
me
nt
s

an
d

ne
x
t
E
l
em
e
nt

i
s
us
e
df
o
r
ex
t
r
a
ct
i
n
gt
h
estrings separated by “/”delimeter
StringTokenizerstrToken = new StringTokenizer(date, "/");

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();
}

public static void main(String[] args)


{
System.out.println("Enter the customer detail");
customer[] cus=new customer[30];
Scanner sc =new Scanner(System.in);

Page
DAA LAB 18CSL4

System.out.println("enter the number of


customer");int n=sc.nextInt();

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:

Enter the customer


detailenter the number
of customer 2
Enter the customer name and
datemonika
12/2/2017
gowda11/4/201
7
monika,12,2,201
7
gowda,11,4,201
7

Page
DAA LAB 18CSL4

Outcomes: On completion of this Program, the students are able to :

 Develop a program that can be solved to store the irname and


date_of_birthinside Java class called Customer

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.*/

Objectives: This Program enable students to :

 LearnInheritance,Exceptionconceptsandtoreadtwointegersa andb andtoCompute


a /b and print, whenb is not zero. Raise an exception whenb is equal to zero.
A lgorit
h m :
// Input: values of two operand i.e a and b
//Output: a) answer displayed when b!=0

b) Arithmetic exception raised and error message displayed when b = 0.


Steps
:
1
)
A clas
s is crea t
ed co n
t
a
i
ni
n
gt
hem
a
i
n
me
th
o
d
2
)
T wo v
ariab l
e s ar
e d e c
l
a
r
edi
.
e
.aa
n
d
b
3
)
Input i
s ob t
a i
n ed fro m
c
on
so
l
e
Scanner sc = new
Scanner(System.in );

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

Outcomes: On completion of this Program, the students are able to :

 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

/* 3B. Write a Java program that implements a multi-thread application that


hashtree threads. First thread generates a random integer for every 1 second;
second thread computesthe square of the number and prints; third thread will print
the value of cube of the number.*/ thread3.start();}}

Objectives: This Program enable students to :


 Learn Inheritance and Thread concepts injava

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.*;

class second implements Runnable


{
publicint x;
public second (int x)
{
this.x=x;
}
public void run()
{
System.out .println("Second thread:Square of the number is"+x*x);
}
}
class third implements Runnable
{
publicint x;
public third(int x)
{
this.x=x;

Page
DAA LAB 18CSL4

public void run()


{
System.out .println("third thread:Cube of the number is"+x*x*x);
}
}
class first extends Thread
{
public void run()
{
intnum=0;
Random
r=newRandom();try
{

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());

}
}
}

public class multithread


{
Public static void main(String args[])
{
first a=new
first();a.start();
}

Page
DAA LAB 18CSL4

O
U
T
P
U
T:

first thread generated number is 65


Secondthread:Squareofthenumberis422
5 third thread:Cube of the number is
274625first thread generated number
is33
Second thread:Square of the
numberis1089third thread:Cube of the
number is 35937 first thread generated
number is30
Second thread:Square of the number is
900third thread:Cube of the number is
27000 first thread generated number is
29
Secondthread:Squareofthenumberi
s841
thirdthread:Cubeofthenumberis24
389first thread generated number
is93
Second thread:Square of the number is
8649 third thread:Cube of the number is
804357

Page
DAA LAB 18CSL4

Outcomes: On completion of this Program, the students are able to :


 Apply Inheritance and Thread concepts injava

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.*/

Objectives: This Program enable students to :


• Learn Quick sorting and searchingtechniques.
• Get exposed to Quick Sort algorithm designtechniques.

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.

A[0]…A[s-1] A[s] A[s+1]…A[n-1]

Allare<=A[s] all are>=A[s]

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

s ← partition ( A [l...r ] ) //s in a split position


Quicksort (A[l ...s -1])
Quicksort ( A [s+1...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

// Input :A sub-array A [l...r ] of A [0...n-1], defined by its left and


rightIndicesl andr (l<r )
// Output :A partition of A [l...r ], with the split position returned as this
function’s value

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

swap ( A [i] , A [j] )


/
/
un
d
ot
h
el
a
st
s
wa
p
wh
e
n
i
>=
j
swap ( A [l ] , A [j] )
ret
urn j

Page
DAA LAB 18CSL4

PROG R A M
Import java.util.Random;
import java.util.Scanner;

public class quicksort{

static int max=2000;


int partition (int[] a, intlow,int high)
{
intp,i,j,temp;
p=a[low];
i=low+1; j=high;
while(low<high)
{
while(a[i]<=p&&i<high) i++;
while(a[j]>p)
void sort(int[] a,intlow,int high)
{

if(low<high)
{
int s=partition(a,low,high);
sort(a,low,s-1);
sort(a,s+1,high);
}
}

public static void main(String[] args) {


// TODO Auto-generated method

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

Outcomes: On completion of this Program, the students are able to :

• Solve problems by applying Quick Sortalgorithms.

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.

Merge sortrequiresanauxiliaryarraytodothe merging.Themergingoftwosubarrays,which are


already sorted, into an auxiliary array can be done in O(n) where n is the total number of
elementsinboththesubarrays.Thisispossiblebecauseboththesubarraysaresorted.

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;

whilei < p and j < q do


ifB[i] <= C[j]
A[k] ← B[i] ; i ← i + 1
elseA[k] ← C[j] ; j ← j + 1
k←k+1
ifi = p
copy C[j...q-1] to A[k...p+q-1]
else copy B[i...p-1] to A[k...p+q-q]

T
i
m
eCom p l
e xi
t y
C (n) € Θ (nlogn)

Mergesort is a perfect example of a successful application of the divide-and-conquer


technique. Thesteps followed in merge sort are:

 Mergesortworksbydividingthegivenarrayintotwosubarraysofequalsize

 The sub arrays are sorted independently usingrecursion

 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.

NOTE: IN MERGE SORT ELEMENTS ARE DIVIDED ACCORDING TO THEIRPOSITION.

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];

public static void main(String[] args)


{
Scanner input = new
Scanner(System.in);
System.out.print("Enter Max array size:
");int n = input.nextInt();
Randomrandom=newRandom() ;
for (int i = 0; i < n;i++)
a[i] = input.nextInt(); // for keyboard entry
a[i] = random.nextInt(1000); // generate random
numbers –long startTime =
System.nanoTime();
MergeSortAlgorithm(0, n - 1);
longstopTime = System.nanoTime();
long elapsedTime = stopTime -
startTime;
System.out.println(" ");
System.out.println("Time Complexity (ms) for n = " + n + " is :" + (double)
elapsedTime / 1000000);
System.out.println("\n-------SortedArray(MergeSort) \n");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
input.close();
}

public static void MergeSortAlgorithm(int low, int high)


{
int mid;
if (low < high)
{
mid = (low + high) / 2;
MergeSortAlgorithm(low, mid);
MergeSortAlgorithm(mid + 1,
high);Merge(low, mid, high);
}
}
Page
DAA LAB 18CSL4

public static void Merge(int low, int mid, int high)


{
int[] b = newint[MAX];
inti, h, j,k;
h = i = low;
j = mid +1;
while ((h <= mid) && (j <= high))
if (a[h] < a[j])
b[i++] = a[h++]; else

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];

for (k = low; k <= high; k++)


a[k] = b[k];
}
}

Page
DAA LAB 18CSL4

OU TP UT 1:
Enter Max array size: 6

The array elements are generated randomly:

-- -- -- -- -- --
Time Complexity (ms) for n = 6 is :0.307211

-------Sorted Array (Merge Sort)-----------------

120 123 240 342 730 968

BUILD SUCCESSFUL (total time: 12 seconds)

Outcomes: On completion of this Program, the students are able to :


• Solve problems by applying Merge Sortalgorithms

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

Objectives: This Program enable students to :

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:

// Initialization of first column and first row

elementsRepeat for i = 0 to n

set V(i,0) = 0
Repeat for j = 0 toW
Set V(0,j) =0
//complete remaining entries

rowbyrowRepeat for i = 1 ton

repeat for j = 1 toW


if(wi<=j)V(i,j))=max{V(i-1,j),V(i-1,j-wi)+vi} if (

wi>j) V(i,j) =V(i-1,j)

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

public static void main(String args[])


{
w = new int[MAX];
p = new int[MAX];
V = new int [MAX][MAX];
Keep = new int[MAX][MAX];
intoptsoln;
ReadObjects();
for (int i = 0; i <= M;i++)V[0][i]
= 0;
for (int i = 0; i <= n;i++)
V[i][0] =0;
optsoln = Knapsack();
System.out.println("Optimal solution = " + optsoln);
}
staticint Knapsack()
{
int r; // remaining Knapsack
capacityfor (int i = 1; i <= n; i++)
for (int j = 0; j <= M; j++)
if ((w[i] <= j) && (p[i] + V[i - 1][j - w[i]] > V[i - 1][j]))
{else

V[i][j] = p[i] + V[i - 1][j - w[i]];


Page
DAA LAB 18CSL4
Keep[i][j] = 1;

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];
}

static void ReadObjects()


{
Scanner scanner = new Scanner(System.in); System.out.println("Knapsack
Problem - Dynamic Programming Solution: ");
System.out.println("Enterthemaxcapacityofknapsack:")
;M=scanner.nextInt();
System.out.println("Enternumberofobjects:");n=
scanner.nextInt();
System.out.println("Enter
Weights:");for(inti = 1; i <= n;i++)
w[i] = scanner.nextInt();
System.out.println("Enter
Profits:");for(inti = 1; i <= n; i++)
p[i] =
scanner.nextInt();
scanner.close();
}
}

Page
DAA LAB 18CSL4

O
U
T
P
U
T1
:

Knapsack Problem - Dynamic Programming


Solution: Enter the max capacity of knapsack:

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)

Outcomes: On completion of this Program, the students are able to :

 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.*/

Objectives: This Program enable students to :

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.

//Output: The value of an optimal feasible subset of the first i items.

//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.

When the capacity is zero, profit is also

zero.When the weight is zero , profit is

also zero.

When knapsack capacity is less than weight then profit is the previous

profitWhen all above cases fails then the formula to be applied is

Profit = Max (profit by previous object for capacity j,

profit by current object+ profit by previous object for current weight

difference)where weight difference=capacity-weight.

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

public static void main(String args[]) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enternumberofobjects:"); n
=scanner.nextInt();
KObject[]obj=newKObject[n];
for(int i = 0;i<n;i++)
obj[i] = new KObject();// allocate memory for members

ReadObjects(obj)
;Knapsack(obj);
scanner.close();
}

static void ReadObjects(KObjectobj[])


{KObject temp = new KObject();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the max capacity of
knapsack: ");M = scanner.nextFloat();

System.out.println("Enter Weights: ");


for (int i = 0; i < n; i++)
obj[i].w = scanner.nextFloat();

System.out.println("Enter Profits:
");for (int i = 0; i < n; i++)
obj[i].p = scanner.nextFloat();

for (int i = 0; i < n; i++)


obj[i].r = obj[i].p / obj[i].w;

Page
DAA LAB 18CSL4
// sort objects in descending order, based on
p/w ratiofor(int i = 0; i<n-1; i++)

for(int j=0; j<n-1-i; j++)


if(obj[j].r <obj[j+1].r){
temp = obj[j];
obj[j] = obj[j+1];
obj[j+1] = temp;
}

scanner.close
();
}

static void Knapsack(KObjectkobj[])

{float x[] = new float[MAX];


floattotalprofi
t;int i;
float U; // U place holder for
MU = M;
totalprofit = 0;
for (i = 0; i < n; i++)
x[i] = 0;
for (i = 0; i < n; i++) {
if (kobj[i].w > U)
break;
else
{ x[i] = 1;
totalprofit = totalprofit + kobj[i].p;
U = U - kobj[i].w;

}
}
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:

Enter number of objects:


4
Enter the max capacity of knapsack:
5
Enter Weights:
3
1
2
4
Enter Profits:
5
4
3
2
i=2
The Solution
vector, x[ ]: 1.0
1.0 0.5 0.0
Total profit is = 10.5

BUILD SUCCESSFUL (total time: 10 minutes 5 seconds)

Outcomes: On completion of this Program, the students are able to :

 Solve 0/1 Knapsack problem using Greedy method to implement injava

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.*/

Objectives: This Program enable students to :


 LearnDijkstra'ssortingandsearchingtechniquestofindshortestpa
ths. Getexposed to Dijkstra's algorithm designtechnique

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

Sv: starting vertex. Dv: destination vertex.

Page
DAA LAB 18CSL4

A
i
m
:
A l
g orit
h m :
// Input: A weighted connected graph G ={V,E}, source s

// Output dv: the distance-vertex matrix


•R
e
ad
n
u
mb
e
r
o
fv
e
r
ti
c
es
of
g
r
ap
h
G

•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

v = next vertex with minimum dv value, by calling


FindNextNear()Add v to tree.

For all the adjacent u of v and u is not added to the


tree, if dv[u]> dv[v]+wt_graph[v,u]
then
dv[u]=dv[v]+wt_graph[v,u]andprev[u]=v.
findNextNear

//Input: graph, dv matrix

//Output: j the next nearest vertex

ominm = 9999 o For k =1 to n


ifkvertexisnotselectedint
ree
and if dv[k] <minm

{ 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];

public void dijk(int[][]a, int s, int n)


{
int u=-1,v,i,j,min;
for(v=0;v<n;v++)
{
d[v]=99;
p[v]=-1;
}
d[s]=0;
for(i=0;i<n;i++){
min=99;
for(j=0;j<n;j++){ if(d[j]<min&
& visited[j]==0)
{
min=d[j]; u=j;
}
}
visited[u]=1;
for(v=0;v<n;v++){
if((d[u]+a[u][v]<d[v])&&(u!=v)&&visited[v]==0)
{
d[v]=d[u]+a[u][v]; p[v]=u;
}
}

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[]

args) {int a[][]=new int[10][10];

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:

enter the number of vertices


5enter the weighted matrix
0 3 99 7 99
3 0 4 299
99 4 0 56
52504
99 99 6 4 0
enter the source vertex 0
the shortest path between source0to remaining vertices are

0 ->1 =3
0 ->1 ->2=7
0 ->1 ->3=5
0 ->1 ->3 ->4 =9

Page
DAA LAB 18CSL4

Outcomes:On completion of this Program, the students are able to :


 Solve Dijkstra's sorting and searching techniques to find shortestpaths.
 Develop a program that can be solved to Dijkstra's algorithm designtechniques.

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

/* 8. Find Minimum Cost Spanning Tree of a given undirected graph using


Kruskal'salgorithm. Implement the program in Java language. */

Objectives:This Program enable students to :

 Learn Kruskal's algorithm to find shortestpaths.


 FindMinimumCostSpanningTreeofagivenundirectedgraphusingKru
skal's a
lgori
th m

Kruskal’s algorithm looks at a minimum spanning three for a weighted connected


graph G=(V,E) as an acyclic sub graph with V-1 edges for which the sum of the edge
weights is the smallest.

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;
}

System.out.println("The cost of minimum spanning tree =

"+sum);public static void main(String[] args) {


int a[ ][ ]=new int[10][10];
inti,j;
System.out.println("Enter the number of vertices of the graph");
Scanner sc=new Scanner(System.in);
int n; n=sc.nextInt();
System.out.println("Enter the wieghted matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt(); kruskal
k=newkruskal(); k.krkl(a,n);
sc.close();

}
}
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

Outcomes: On completion of this Program, the students are able to :


 Solve Kruskal's algorithm to find shortestpaths.
 SolveMinimumCostSpanningTreeofagivenundirectedgraphusingKru
skal's a
l
g or
it
hm

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.

Objectives: This Program enable students to :

 Learn Prim's algorithm to find shortestpaths.


 Find Minimum Cost Spanning Tree of a given undirected graphusing Prim'salgorithm
Choose a node and build a tree from there selecting at every stage the shortest available
edge thatcan extend the tree to an additional node.

•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

public class prims {


public static void main(String[]
args) {int w[ ][ ]=new int[10][10]; int
n,i,j,s,k=0;
int min;
int sum=0;
intu=0,v=0;
int flag=0;
int sol[ ]=new int[10];
System.out.println("Enter the number of
vertices"); Scanner sc=new Scanner(System.in);
n=sc.nextInt();for(i=1;i<=n;i++)
sol[i]=0;
System.out.println("Enter the weighted graph");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=sc.nextInt();
System.out.println("Enter the source vertex");
s=sc.nextInt();
sol[s]=1;
k=1;
while (k<=n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sol[i]==1&&sol[j]==0)
if(i!=j&&min>w[i][j])
{
min=w[i][j];
u=i;
v=j;
}
sol[v]=1;

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

Outcomes: On completion of this Program, the students are able to :

 Solve Prim’s algorithm to find shortest paths.


 SolveMinimumCostSpanningTreeofagivenundirectedgraphusingPrim’salgorithm

V
i
v
aq
ue
s
t
i
o
ns

 What is the difference between Prims and Kruskalsalgorithm?


 Can we use kruskals to find maximum cost spanningtree.
 What is minimum cost spanningtree.

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
.
*/

Objectives: This Program enable students to :

 Learn Floyd’s algorithm to findAll-Pairs Shortestpaths.


 FindMinimumCostSpanningTreeofagivenundirectedgraphusingFloyd’salgorithm

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

// Input: Weight matrix W

// Output: Distance matrix of shortest paths’

lengthD(0)w
fork1 to n do
fori1 to n do
forj1 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]);
}

public static void main(String[]


args) {int a[ ][ ]=new int[10][10];
intn,i,j;
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=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
floyd f=new floyd();
f.flyd(a, n);
System.out.println("Theshortestpathmatri
xis");for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
sc.close();

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:

 Solve Floyd’salgorithm to findAll-Pairs Shortest paths.


 Solve &Find Minimum Cost Spanning Tree ofa given undirected graph using Floyd’s
al
g orit
h m

V
i
v
aq
ue
s
t
i
o
ns

 Floyd’s algorithm is an example of which typeofalgorithm.


 Difference between Floyds and Dijkstra’salgorithm.
 What is the time complexity of Floyd’salgorithm?
 What is the best,worst and average case of Floyd’salgorithm?

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 :

 Learn Travelling Sales Person problem.


 Find Minimum Traveling Distance using Dynamicprogramming

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.

C(S, i) = min { C(S-{i}, j) + dis(j, i)} where j belongs to S, j != i and j!=1.

Page
DAA LAB 18CSL4
PRO GR AM

importjava.util.Scanner;

public class TSP {


staticint MAX = 100;
static final int infinity = 999;

public static void main(String


args[]) {int cost = infinity;
intc[][] =new int[MAX][MAX]; // cost
matrixinttour[] =newint[MAX]; //
optimaltour
intn; // max.cities
System.out.println("Travelling Salesman Problem using
DynamicProgramming\n");
System.out.println("Enter number of cities: ");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
System.out.println("Enter Cost
matrix:\n");for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
c[i][j] = scanner.nextInt();
if (c[i][j] == 0)
c[i][j] = 999;
}
for (int i = 0; i < n; i++)
tour[i] = i;
cost = tspdp(c, tour, 0, n);
// print tour cost and tour
System.out.println("Minimum Tour Cost: " +
cost);System.out.println("\nTour:");
for (int i = 0; i < n; i++) {
System.out.print(tour[i] + " -> ");

Page
DAA LAB 18CSL4
}

Page
DAA LAB 18CSL4

System.out.println(tour[0] +
"\n");scanner.close();
}

staticinttspdp(int c[][], int tour[], int start, int n)


{int i, j, k;
inttemp[] = new int[MAX];
intmintour[] = newint[MAX];
intmincost;
int cost;
if (start == n - 2)
return c[tour[n - 2]][tour[n - 1]] + c[tour[n - 1]][0];
mincost = infinity;
for (i = start + 1; i < n; i++)
{for (j = 0; j < n; j++)
temp[j] = tour[j];
temp[start + 1] = tour[i];

temp[i] = tour[start + 1];


if (c[tour[start]][tour[i]] + (cost = tspdp(c, temp, start + 1, n)) <mincost)
{
mincost = c[tour[start]][tour[i]] + cost;
for (k = 0; k < n; k++)
mintour[k] = temp[k];
}
}
for (i = 0; i < n; i++)
tour[i] = mintour[i];
return mincost;
}
}

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

BUILD SUCCESSFUL (total time: 21 seconds)

Program Outcomes: On Completion of these Program :

 Study Travelling Sales Person problem.


 Study Minimum Traveling Distance using Dynamicprogramming

V
i
v
aq
ue
s
t
i
o
ns

 Application of travelling salesmenproblem.


 What is the time complexity ofTSP?
 How TSP is different from Dijkstras, Prims and Kruskalsalgorithm

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.
*/

Objectives:This Program enable students to :

 Learn Subset problem.


 Find SUM is equal to a given positive integer

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.

This problem is NP-complete.


This problem arises in practical applications. Similar to the knapsack problem we may
have a truck that can carry at most t pounds and we have n different boxes to ship and
the ith box weighs xi pounds. The naive approach of computing the sum of the
elements of every subset ofS and then selecting the best requires exponential time.
Below we present an exponential time exact algorithm.


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

//generating left child that means including k in solution


•S
e
tx
[
k]
=
1
•I
f
(
s+s
[
k
]=
d)
t
h
en
s
ub
s
e
t
f
ou
n
d
,p
r
i
nt
s
o
lu
t
i
on

•I
f
(
s+s
[
k
]+
s[
k
+1
]
<=
d
)

thenSumOfSum(s+

s[k],k+1,r–s[k])

//Generate right child i.e. element k absent

•I
f
(
s+
r
-
s[
k
]
>=
d)
A
N
D(
s
+
s[k+1])<=dTHEN {x[k]=0;

SumOfSub(s, k+1, r – s[k])

Page
DAA LAB 18CSL4

P
R
O
G
RA
M

importjava.util.Scanner;
import static java.lang.Math.pow;

public class subSet {

void subset(intnum,int n, int x[])


{
int i; for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}

public static void main(String[] args) {


// TODO Auto-generated method
stubinta[]=new int[10];
int x[]=new int[10];
intn,d,sum,present=0; int j;
System.out.println("enter the number of elements of set");
Scannersc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("enter the elements of set"); for(int
i=1;i<=n;i++)
a[i]=sc.nextInt();
System.out.println("enter the positive integer sum");
d=sc.nextInt();
if(d>0)
{
for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subSet s=new
subSet();
s.subset(i,n,x);
sum=0; for(j=1;j<=n;j++)
if(x[j]==1)sum=sum+a[j];

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:

enter the number of elements of


set 5enter the elements of set 1 2
5 6 8 enter the positive integer
sum 9 Subset={1,8,}=9
Subset={1,2,6,}=9

Outcomes :This Program enable students to :

 Study Subset problem.


 Study SUM is equal to a given positiveinteger

V
i
v
aq
ue
s
t
i
o
ns

 Solve the given problem for subset sum int[] A = { 3, 2, 7, 1}, S =6


 Give the time complexity equation for subsetsum.
 Subset problem can be solved by using which type ofalgorithm.
 What is the difference between Backtracking and Branch and boundalgorithm?

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 :

To find Hamiltonian Cycle in an undirected Graph G ofn vertices.


A
l
g
or
i
t
hm
:
Input:
A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is
adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct
edgefrom i to j, otherwise graph[i][j] is 0.

Output:
An array path[V] that should contain the Hamiltonian Path. path[i] should represent
theith
vertexintheHamiltonianPath.ThecodeshouldalsoreturnfalseifthereisnoHamiltonian
Cyclein thegraph.

B acktrac king Algori


th m
Create an empty path array and add vertex 0 to it. Add other vertices, starting from the
vertex 1.Beforeadding
avertex,checkforwhetheritisadjacenttothepreviously
addedvertexand
notalreadyadded.Ifwefindsuchavertex,weaddthevertexaspartofthesolution.Ifwedo not
find a vertex then we returnfalse.

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();
}

public void nextValue (int k)


{
int i=0;
while(true)
{
x[k]=x[k]+1;
if (x[k]==n)
x[k]=-1;
if (x[k]==-1)
return;
if (adj[x[k-1]][x[k]]==1)
for (i=0; i<k; i++)
if (x[i]==x[k])
break;
if (i==k)
if (k<n-1 || k==n-1 &&adj[x[n-1]][0]==1)
return;
}
}

Page
DAA LAB 18CSL4

public void getHCycle(int k)


{
while(true)
{
nextValue(k);
if (x[k]==-1)
return; if (k==n-1)
{
System.out.println("\nSolution :
");for (int i=0; i<n; i++)
System.out.print((x[i]+1)+" ");
System.out.println(1);
}
elsegetHCycle(k+1);
}
}

}
classHamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycleobj=new
Hamiltoniancycle();obj.getHCycle(1);
}
}

Page
DAA LAB 18CSL4

O
u
t
p
u
t:

Enter the number of


nodes 6Enter the
adjacency matrix
011 1 0 0
101 0 0 1
110 1 1 0
101 0 1 0
001 1 0 1
010 0 1 0

Solution:
1265341
Solution:
1265431
Solution:
1326541
Solution:
1345621
Solution:
1435621
Solution:
1456231

Outcomes: On Completion of these Program enable students to : Solve

Hamiltonian Cycle in an undirected Graph G ofn vertices.

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

You might also like