You are on page 1of 103

B.

ScComput
erSci
ence
I
VSEMESTER
Paper
-I
V:DATASTRUCTURES
UNI TI
ConceptofAbst ractDat aTy pes( ADTs) -DataTy pes, Dat aSt r
uct ures,StorageSt ructures, andFile
Struct ures, Pr i
mi t
iveandNon- primi ti
v eDataSt ructures, LinearandNon- l
inearDat aStructures.
LinearLi sts–ADT, ArrayandLi nkedr epresentations, Pointers.
Array s–OneDi mensional -TwoDi mensi onal-MultiDimensi onal-Oper at
ions-Spar seMat r
ices.
LinkedLi sts: SingleLinkedLi st,Doubl eLinkedLi st,CircularLinkedLi st,applications
UNI TI I
Stacks: Def i
ni t
ion,ADT, ArrayandLi nkedr epresentations, Impl ement ati
onsandAppl ications
Queues: Def ini
tion,ADT, ArrayandLi nkedr epresentations, CircularQueues, Dequeues, Priori
tyQueues,
Impl ement at i
onsandAppl i
cations.
UNI TI II
Trees: BinaryTr ee,Definiti
on, Proper ti
es,ADT, ArrayandLi nkedr epresent at
ions, Implement ationsand
Appl ications.Bi nar ySear chTr ees( BST)–Def i
niti
on, ADT, Oper ati
onsandI mpl ement ations,BST
Appl ications.Thr eadedBi naryTr ees, Heapt r
ees.
UNI TI V
Graphs–Gr aphandi tsRepr esent ation,GraphTr av ersals,Connect edComponent s,
Basi cSear chi
ng
Techni ques, Mi nimal Spanni ngTr ees
UNI T-V
Sor
ti
ngandSear
chi
ng:
Sel
ect
ion,
Inser
ti
on,
Bubbl
e,Mer
ge,
Qui
ck,
Heapsor
t,Sequent
ial
andBi
nar
y
Sear
chi
ng.
2

UNI
TI
ConceptofAbst
ractDat
aTy
pes(
ADTs)
Forthecart hatwedr ive,mostofuswantt oknowhowt ostartt hecaranddr ivei t
.Mostpeopl earenot
concer nedwi ththecompl exityofhowt heengi newor ks.Bysepar ati
ngt hedesigndet ail
sofacar ’
sengi ne
from itsuse,t hemanuf acturerhelpst hedr i
verfocusonhow t odr ivet hecar .Ourdai l
yl i
fehasot her
simil
arexampl es.Forthemostpar t,wear econcer nedonl ywi t
hhowt ousecer tainitems,rathert
hanwi th
howt heywor k.
Separatingt hedesigndet ai
ls(
thati s,howt hecar ’senginewor ks)from it
susei scal
ledabstracti
on.
Inotherwor ds, abst
ractionfocusesonwhatt heengi nedoesandnotonhowi twor ks.Thus,abstr
actionis
thepr ocessofsepar atingt helogicalpr opert
iesf r
om t hei mpl ement ati
ondet ai
ls.Dr i
vi
ngt hecari sa
l
ogicalpr oper ty;t
heconst r ucti
onoft heengi neconst i
tutest hei mpl ementat i
ondet ai
ls.Wehav ean
abstractviewofwhatt heengi nedoes, butar enotinterestedint heengi ne’sactuali mplementati
on.

Abst
ractDat
aty
pe(
ADT)
:
An abst
ractdat
aty
pe i
s a dat
aty
pe t
hatsepar
ates t
he l
ogi
calpr
oper
ti
es f
rom t
he
i
mpl
ement
ati
ondet
ail
s.Li
keanyot
herdat
aty
pe,anADThast
hreet
hingsassoci
atedwi
thi
t:t
he
nameoft
heADT,
cal
l
edt
het
ypename;t
hesetofv
aluesbel
ongi
ngt
otheADT,
cal
l
edt
hedomai
n;
andt
hesetofoper
ati
onsont
hedat
a.
Forexampl
e,st
acksandqueuesar
eper
fectexampl
esofanADT.Wecani
mpl
ementbot
h
t
heseADTsusi
nganar
rayoral
i
nkedl
i
st.Thi
sdemonst
rat
est
he‘
abst
ract
’nat
ureofst
acksand
queues.
Thedef
ini
ti
onofADTonl
yment
ionswhatoper
ati
onsar
etobeper
for
medbutnothowt
hese
oper
ati
onswi
l
lbei
mpl
ement
ed.I
tdoesnotspeci
fyhow dat
awi
l
lbeor
gani
zedi
nmemor
yand
whatal
gor
it
hmswi
l
lbeusedf
ori
mpl
ement
ingt
heoper
ati
ons.I
tiscal
l
ed“
abst
ract
”becausei
t
gi
vesani
mpl
ement
ati
oni
ndependentv
iew.Thepr
ocessofpr
ovi
dingonl
ytheessent
ial
sand
hi
dingt
hedet
ail
sisknownasabst
ract
ion.

Ther
emaybet
housandsofway
sinwhi
chagi
venADTcanbei
mpl
ement
ed,ev
enwhent
he
codi
ngl
anguager
emai
nsconst
ant
.Anysuchi
mpl
ement
ati
onmustcompl
ywi
tht
hecont
ent
-wi
se
andbehav
ior
aldescr
ipt
ionoft
heADT.
Forexampl
e,i
nteger
sar
eanADT,
def
inedast
hev
alues0,
1,−1,
2,2,
...
,andbyt
heoper
ati
ons
ofaddi
ti
on,subt
ract
ion,mul
ti
pli
cat
ion,anddi
vi
sion,t
oget
herwi
thgr
eat
ert
han,l
esst
han,et
c.
whi
char
eindependentofhowt
hei
ntegersar
erepr
esent
edbythecomputer
.
ToimplementanADT,wemustr epr
esentt
hedat aandwrit
ealgori
thmst
oper
for
mthe
oper
ati
ons.

Dat
aSt
ruct
ures:
Dat
ast
ruct
urei
sar
epr
esent
ati
onofl
ogi
calr
elat
ionshi
pexi
sti
ngbet
weeni
ndi
vi
dualel
ement
s
3

ofdat
a.I
not
herwor
ds,adat
ast
ruct
uredef
inesawayofor
gani
zi
ngal
ldat
ait
emst
hatconsi
der
s
notonl
ytheel
ement
sst
oredbutal
sot
hei
rrel
ati
onshi
ptoeachot
her
.Thet
erm dat
ast
ruct
urei
s
usedt
odescr
ibet
hewaydat
aisst
ored.
Todev
elopapr
ogr
am ofanal
gor
it
hm weshoul
dsel
ectanappr
opr
iat
edat
ast
ruct
uref
ort
hat
al
gor
it
hm.Ther
efor
e,dat
ast
ruct
urei
srepr
esent
edas:
Al
gor
it
hm +Dat
aSt
ruct
ure=Pr
ogr
am
Adat
ast
ruct
urei
ssai
dtobel
i
neari
fit
sel
ement
sfr
om asequenceoral
i
nerl
i
st.Thel
i
near
dat
ast
ruct
uresl
i
keanar
ray
,st
acks,queuesandl
i
nkedl
i
stsor
gani
zedat
ainl
i
nearor
der
.Adat
a
st
ruct
urei
ssai
dtobenonl
i
neari
fit
sel
ement
sfr
om ahi
erar
chi
calcl
assi
fi
cat
ionwher
edat
ait
ems
appearatv
ari
ousl
evel
s.
Tr
eesandGr
aphsar
ewi
del
yusednon-
leanerdat
ast
ruct
ures.Tr
eesandgr
aphst
ruct
ures
r
epr
esent
shi
erar
chi
calr
elat
ionshi
pbet
weeni
ndi
vi
dualdat
ael
ement
s.Gr
aphsar
enot
hingbut
t
reeswi
thcer
tai
nrest
ri
cti
onsr
emov
ed.
Ther
ear
edi
ff
erentt
ypesofdat
ast
ruct
urest
hatt
heJav
alanguagesuppor
ts.Whi
l
eonet
ypeof
dat
ast
ruct
uremayper
mitaddi
ngofnewdat
ait
emsonl
yatt
hebegi
nni
ng,
theot
herwayal
l
owi
tto
beaddedatanyposi
ti
on.Whi
l
eonedat
ast
ruct
uremayal
l
owaccessi
ngdat
ait
emssequent
ial
l
y,
t
heot
hermayal
l
owr
andom accessofdat
a.

CLASSI
FICATI
ONOFDATASTRUCTURES:
Dat
ast
ruct
uresar
edi
vi
dedi
ntot
wot
ypes:
 Pr
imi
ti
vedat
ast
ruct
ures.
 Non-
pri
mit
ivedat
ast
ruct
ures.

Dat
aSt
ruct
ures

Pr
imi
ti
veDat
aSt
ruct
ures Non-
Pri
miti
veDat
a
St
ruct
ures

I
nteger Fl
oat Char Poi
nter Ar
ray
s Li
sts Fi
l
es
s

Li
nearLi
sts Non-
Linear
Li
sts

St
ack Queue Gr
aph Tr
ee
s s s s
Pr
imi
ti
veDat
aSt
ruct
ures:
4

Pr
imi
ti
vedat
ast
ruct
uresar
ethebasi
cdat
ast
ruct
urest
hatdi
rect
lyoper
ateupont
hemachi
ne
i
nst
ruct
ions.Theyhav
e di
ff
erentr
epr
esent
ati
on on di
ff
erentcomput
ers.I
nteger
s,f
loat
ing poi
nt
number
s,char
act
erconst
ant
s,st
ri
ngconst
ant
sandpoi
nter
scomeundert
hiscat
egor
y.
Non-
pri
mit
iveDat
aSt
ruct
ures:
Non-
pri
mit
ivedat
ast
ruct
uresar
emor
ecompl
i
cat
eddat
ast
ruct
uresandar
eder
ivedf
rom pr
imi
ti
ve
dat
ast
ruct
ures.Theyemphasi
zeongr
oupi
ngsameordi
ff
erentdat
ait
emswi
thr
elat
ionshi
pbet
ween
eachdat
ait
em.Ar
ray
s,l
i
stsandf
il
escomeundert
hiscat
egor
y.

Li
nearandNon-
li
nearDat
aSt
ruct
ures
Non-
pri
mit
ivedat
ast
ruct
urescanf
urt
herbecl
assi
fi
edi
ntot
wocat
egor
ies:l
i
nearandnon-
l
i
neardat
ast
ruct
ures.
I
ftheel
ement
sofadat
ast
ruct
urear
est
oredi
nal
i
nearorsequent
ialor
der
,theni
tisal
i
neardat
a
st
ruct
ure.Exampl
esi
ncl
udear
ray
s,l
i
nkedl
i
sts,st
acks,andqueues.Li
neardat
ast
ruct
urescanbe
r
epr
esent
edi
nmemor
yint
wodi
ff
erentway
s.Onewayi
stohav
etoal
i
nearr
elat
ionshi
pbet
ween
el
ement
sbymeansofsequent
ialmemor
ylocat
ions.Theot
herwayi
stohav
eal
i
nearr
elat
ionshi
p
bet
weenel
ement
sbymeansofl
i
nks.
Howev
er,i
ftheel
ement
sofadat
ast
ruct
urear
enotst
oredi
nasequent
ialor
der
,theni
tisanon-
l
i
neardat
ast
ruct
ure.Ther
elat
ionshi
pofadj
acencyi
snotmai
ntai
nedbet
weenel
ement
sofanon-
li
near
dat
ast
ruct
ure.Exampl
esi
ncl
udet
reesandgr
aphs.

Char
act
eri
sti
csofaDat
aSt
ruct
ure

Cor
rect
ness:

Datast
ruct
ureimpl
ement
ati
onshoul
dimpl
ementi
tsi
nter
facecor
rect
ly.
Ti
meCompl ex
ity
:

Runningt
imeort
heexecut
iont
imeofoper
ati
onsofdat
ast
ruct
uremustbeassmal
laspossi
ble.
SpaceCompl
exi
ty:

Memor
yusageofadat
ast
ruct
ureoper
ati
onshoul
dbeasl
i
ttl
easpossi
ble.

Oper
ati
onsonDat
aSt
ruct
ures:
Tr
aver
sal I
tmeanst
oaccesseachdat
ait
em exact
lyoncesot
hati
tcanbepr
ocessed.For
exampl
e,t
opr
intt
henamesofal
lthest
udent
sinacl
ass.
Sear
ch I
tisusedt
ofi
ndt
hel
ocat
ionofoneormor
edat
ait
emst
hatsat
isf
ythegi
ven
const
rai
nt.Suchadat
ait
em mayormaynotbepr
esenti
nthegi
vencol
l
ect
ionofdat
a
i
tems.Forexampl
e,t
ofi
ndt
henamesofal
lthest
udent
swhosecur
ed100mar
ksi
n
mat
hemat
ics.
5

I
nser
ti
on I
tisusedt
oaddnewdat
ait
emst
othegi
venl
i
stofdat
ait
ems.Forexampl
e,t
oaddt
he
det
ail
sofanewst
udentwhohasr
ecent
lyj
oinedt
hecour
se.
Del
eti
on I
tmeanst
oremov
e(del
ete)apar
ti
cul
ardat
ait
em f
rom t
hegi
vencol
l
ect
ionofdat
a
i
tems.Forexampl
e,t
odel
etet
henameofast
udentwhohasl
eftt
hecour
se.
Sor
ti
ng Dat
ait
emscanbear
rangedi
nsomeor
derl
i
keascendi
ngor
derordescendi
ngor
der
dependi
ngont
het
ypeofappl
i
cat
ion.Forexampl
e,ar
rangi
ngt
henameofst
udent
sina
cl
assi
nanal
phabet
icalor
der
,orcal
cul
ati
ngt
het
opt
hreewi
nner
sbyar
rangi
ngt
he
par
ti
cipant
s’scor
esi
ndescendi
ngor
derandt
henext
ract
ingt
het
opt
hree.
Mer
ging Li
stsoft
wosor
teddat
ait
emscanbecombi
nedt
ofor
m asi
ngl
eli
stofsor
teddat
a
i
tems.Forexampl
e,i
fwewantt
odel
etet
hedet
ail
sofast
udentwhosenamei
sV,
then
wef
ir
sthav
etosear
cht
hel
i
stofst
udent
stof
indwhet
hert
her
ecor
dofXexi
stsornot
andi
fitexi
stst
henatwhi
chl
ocat
ion,sot
hatt
hedet
ail
scanbedel
etedf
rom t
hat
par
ti
cul
arl
ocat
ion.

2.Li
nearLi
sts
Poi
nter
s:
Ev
eryv
ari
abl
ehasanameandav
alueassoci
atedwi
thi
t.Whenav
ari
abl
eisdecl
ared,a
speci
fi
cbl
ockofmemor
ywi
thi
nthecomput
eri
sal
l
ocat
edt
ohol
dthev
alueoft
hatv
ari
abl
e.The
si
zeoft
heal
l
ocat
edbl
ockdependsont
hedat
aty
pe.
Consi
dert
hef
oll
owi
ngst
atement
.
i
ntx=10;
Whent
hisst
atementexecut
es,
thecompi
l
erset
sasi
de2by
tesofmemor
ytohol
dthev
alue10.
I
tal
soset
supasy
mbolt
abl
einwhi
chi
taddst
hesy
mbolxandt
her
elat
iveaddr
essi
nthememor
y
wher
ethose2by
teswer
esetasi
de.
Thus,
ever
yvar
iabl
ehasav
alueandal
soamemor
ylocat
ion(
commonl
yknownasaddr
ess)
associ
atedwi
thi
t.Theaddr
esscanbeaccessedusi
ngamper
sand(
&)oper
ator
,whi
chdenot
esan
addr
essi
nmemor
y.
Decl
ari
ngPoi
nterVar
iabl
es:
Apoi
nterpr
ovi
desaccesst
ovar
iabl
esbyusi
ngt
headdr
essoft
hatv
ari
abl
e.Apoi
nterv
ari
abl
e
i
sther
efor
eav
ari
abl
ethatst
orest
headdr
essofanot
herv
ari
abl
e.
Thegener
alsy
ntaxofdecl
ari
ngpoi
nterv
ari
abl
escanbegi
venasbel
ow.
dat
a_t
ype*
ptr
_name;
Her
e,dat
a_t
ypei
sthedat
aty
peoft
hev
aluet
hatt
hepoi
nterwi
l
lpoi
ntt
o.Forexampl
e,
i
nt*
pnum;
char*
pch;
f
loat*
pfnum;
6

I
neachoft
heabov
est
atement
s,apoi
nterv
ari
abl
eisdecl
aredt
opoi
ntt
oav
ari
abl
eoft
he
speci
fi
eddat
aty
pe.Al
thoughal
lthesepoi
nter
s(pnum,pch,andpf
num)poi
ntt
odi
ff
erentdat
a
t
ypes,t
heywi
l
loccupyt
hesameamountofspacei
nthememor
y.Buthowmuchspacet
heywi
l
l
occupywi
l
ldependont
hepl
atf
orm wher
ethecodei
sgoi
ngt
orun.
Nowl
etusdecl
areani
ntegerpoi
nterv
ari
abl
eandst
artusi
ngi
tinourpr
ogr
am code.
i
ntx=10;
i
nt*
ptr
;
pt
r=&x;
I
ntheabov
est
atement
,pt
rist
henameoft
hepoi
nterv
ari
abl
e.The*i
nfor
mst
hecompi
l
er
t
hatpt
risapoi
nterv
ari
abl
eandt
hei
ntspeci
fi
est
hati
twi
l
lst
oret
headdr
essofani
ntegerv
ari
abl
e.
Ani
ntegerpoi
nterv
ari
abl
e,t
her
efor
e,‘
poi
ntst
o’ani
ntegerv
ari
abl
e.I
nthel
astst
atement
,pt
ris
assi
gnedt
headdr
essofx.The&oper
atorr
etr
iev
est
hel
val
ue(
addr
ess)ofx,
andcopi
est
hatt
othe
cont
ent
soft
hepoi
nterpt
r.
pt
r=&x,
thenpt
r=1003.
*
ptr=10,
since10i
sthev
alueofx.

3.
Arr
ays
Anar
rayi
sagr
oupofcont
iguousorr
elat
eddat
ait
em t
hatar
eref
erencedbyacommonname.
Fori
nst
ance,wecandef
ineanar
rayname‘
sal
ary
’tor
epr
esentasetofsal
ari
esofagr
oupof
empl
oyees.Apar
ti
cul
arv
aluei
sindi
cat
edbywr
it
i edi
nganumbercal
l ndexnumberorsubscr
ipti
n
br
acket
saf
tert
hear
rayname.Thef
ir
stel
ementi
sref
err
edt
oassal
ary
[0]t
hesecondsal
ary
[1]and
soont
hel
astel
ementwi
l
lbea[
9].
Whi
l
ethecompl
etesetofv
aluesi
sref
err
edt
oasanar
ray
,thei
ndi
vi
dualv
aluesar
ecal
l
ed
el
ement
s.Ar
ray
scanbeofanyv
ari
abl
ety
pe.
Ty
pesofAr
ray
:
1)Si
ngl
edi
mensi
onal
arr
ay
2)Mul
tidi
mensi
onal
arr
ay
OneDi
mensi
onalAr
ray
s:
Al
i
stofi
temscanbegi
venonev
ari
abl
enameusi
ngonl
yonesubscr
iptandsuchav
ari
abl
e
cal
l
edsi
ngl
e-subscr
ipt
edv
ari
abl
eoraone-
dimensi
onalar
ray
.Itcanbev
isual
i
zedasasi
ngl
erow
oracol
umn.
CREATI
NGANARRAY:
Li
keanyot
herv
ari
abl
es,
arr
aysmustbedecl
aredandcr
eat
edi
nthecomput
ermemor
ybef
ore
t
heyar
eused.Cr
eat
ionofanar
rayi
nvol
vest
hreest
eps:
 Decl
ari
ngt
hear
ray
 Cr
eat
ingmemor
ylocat
ion
7

 Put
ti
ngv
aluesi
ntot
hememor
ylocat
ions.
Decl
arat
ionofAr
ray
s:
Ar
ray
sinjavamaybedecl ar
edi
ntwof
orms:
For
m1: t ypearr
ayname[];
For
m2: t ype[]arr
ayname;
Eg: intnumber[]
;
f
loat
[]mar
ks;
Cr
eat
ionofAr
ray
s:
Af
terdecl
ari
nganar
rayweneedt
ocr
eat
eiti
nthememor
y.Jav
aal
l
owsust
ocr
eat
ear
ray
s
usi
ngthenewoper at
or.
Synt
ax: ar r
ayname=new type[]
;
Eg: number=new i
nt[
5];
av
erage=new f
loat
[10]
;
I
tisal
sopossi
blet
ocombi
net
het
wost
eps–decl
arat
ionandcr
eat
ion–i
ntooneasshownbel
ow:
i
ntnumber
[]=newi
nt[
5];

ACCESSI
NGELEMENTSOFTHEARRAY:
Theel
ement
sint
hear
rayar
eaccessedt
hrought
hei
rindex.Forexampl
e,t
oaccesst
hef
our
th
el
ementoft
hear
ray
,wemustwr
it
ear
r[
3].Toaccessal
ltheel
ement
soft
hear
ray
,wemustusea
l
oop.
/
/Seteachel ementoft
hear
rayt
o-1
i
ntmarks[]
=newi nt[
10]
;
f
or(i
nti=0;
i<10;i
++)
{
marks[i
]=-1;
}
Theabov
ecodeaccessesev
eryi
ndi
vi
dual
elementoft
hear
rayandset
sitv
aluet
o-1.
I
nit
ial
i
zat
ionofAr
ray
s:
Thef
inalst
epi
stoputv
aluesi
ntot
hear
raycr
eat
ed.Thi
spr
ocessi
sknownasi
nit
ial
i
zat
ion.
Thisisdoneusingthearr
aysubscr
ipt.
Syntax: ar r
ayname[
subscr
ipt
]=v al
ue;
Eg: number[
0]=35;
number
[1]=40;
Wecanal
soi
nit
ial
i
zat
ionar
ray
saut
omat
ical
l
yint
hesamewayast
heor
dinar
yvar
iabl
eswhen
theyaredecl
ared.Ther
eisnoneedtousethenewoper
ator
Syntax: t ypear r
ayname[]={ li
stofv al
ues}
;
Eg: i
ntnumber[]={10,20,
30,
40,50};

TwoDi
mensi
onal
Arr
ays:
Aone-
dimensi
onalar
rayi
sor
gani
zedl
i
near
lyandonl
yinonedi
rect
ion.Butatt
imes,weneed
8

t
ost
oredat
aint
hef
orm ofmat
ri
cesort
abl
es.Her
etheconceptofone-
dimensi
onalar
rayi
s
ext
endedt
oincor
por
atet
wo-
dimensi
onaldat
ast
ruct
ures.At
wo-
dimensi
onalar
rayspeci
fi
edusi
ng
t
wo subscr
ipt
s wher
e one subscr
iptdenot
es t
wo and t
he ot
herdenot
es col
umn.A t
wo-
di
mensi
onal
arr
aywhi
chcanbev
iewedasanar
rayofar
ray
s.

Fi
rst

di
mension
Seconddi
mensi
on
Decl
ari
ngTwo-
Dimensi
onalAr
rays:
Si
mil
art
oone-
dimensi
onal
arr
ays,
two-
dimensi
onal
arr
aysmustbedecl
aredbef
orebei
ngused.
Thedecl
arat
ionst
atementt
ell
sthecompi
l
ert
henameoft
hear
ray
,thedat
aty
peofeachel
ement
i
nthear
ray
,andsi
zeofeachdi
mensi
on.At
wo-
dimensi
onal
arr
ayi
sdecl
aredas:
Dat
a_t
ypear
ray_
name[][]=newdata_
type[
row_
size][
col
umn_
size]
;
Eg: i ntmyar
ray[][]=newi
nt[
3][
3];
I
nit
ial
i
zat
ionofTwo-
Dimensi
onalAr
ray
s:
Li
ket
heone-
dimensi
onalar
ray
s,t
wo-
dimensi
onalar
ray
smaybei
nit
ial
i
zedbyf
oll
owi
ngt
hei
r
decl
arat
ionwi
thal
i
stofi
nit
ial
val
uesencl
osedi
nbr
aces.Forexampl
e,
i
ntt
abl
e[2]
[3]
={0,
0,
0,
1,
1,
1};
Theabov
est
atementcanbeequi
val
ent
lywr
it
tenas:
i
ntt
abl
e[]
[]={
{0,
0,
0},
{1,
1,
1}}
;

Mul
tiDi
mensi
onal
:
Amul
ti
-di
mensi
onal
arr
ayi
nsi
mpl
eter
msi
sanar
rayofar
ray
s.Li
kewehav
eonei
ndexi
naone
-
dimensi
onal
arr
ay,
twoi
ndi
cesi
nat
wo-
dimensi
onal
arr
ay,
int
hesamewaywehav
eni
ndi
cesi
nan
n-
dimensi
onal
arr
ayormul
ti
dimensi
onal
arr
ay.
Ann-
dimensi
onalm1 xm2 xm3 x….
.mn ar
rayi
sacol
l
ect
ionm1*
m2*
m3*
…..
mn el
ement
s.I
n
mul
ti
dimensi
onal
arr
ay,
apar
ti
cul
arel
ementi
sspeci
fi
edbyusi
ngnsubscr
ipt
sasA[
I1]
[I
2]
[I
3]
…..
[I
n]
.
Thebel
ow exampl
eshowsat
hree-
dimensi
onalar
ray
.Thear
rayhast
hreepages,f
ourr
ows,
andt
wocol
umns.

Q U
R V
Second
S W
dimension I M
(Columns) J N T X

K O
Page
A3 E
Fir
st B F L P
di
mension
(Rows) C G
D H
9

Page2

Page1
Amul
ti
dimensi
onal
arr
ayi
sdecl
aredandi
nit
ial
i
zedsi
mil
art
oone-andt
wo-
dimensi
onal
arr
ays.
Spar
seMat
ri
ces.
I
ncomput
erpr
ogr
ammi
ng,amat
ri
xcanbedef
inedwi
tha2-
dimensi
onalar
ray
.Anyar
raywi
th
m col
umnsandnr
owsr
epr
esent
sam Xnmat
ri
x.Ther
emaybeasi
tuat
ioni
nwhi
chamat
ri
x
cont
ainsmor
enumberofzer
oval
uest
hannon-
zer
oval
ues.Suchmat
ri
xisknownasspar
semat
ri
x.
Spar
semat
ri
xisamat
ri
xthathasl
argenumberofel
ement
swi
thazer
oval
ue.I
nor
dert
o
ef
fi
cient
lyut
il
izet
hememor
y,speci
ali
zedal
gor
it
hmsanddat
ast
ruct
urest
hatt
akeadv
ant
ageof
t
hespar
semat
ri
xshoul
dbeused.
Whenaspar
semat
ri
xisr
epr
esent
edwi
th2-
dimensi
onalar
ray
,wewast
elotofspacet
o
r
epr
esentt
hatmat
ri
x.Forexampl
e,consi
deramat
ri
xofsi
ze100x100cont
aini
ngonl
y10non-
zer
oel
ement
s.I
nthi
smat
ri
x,onl
y10spacesar
efi
l
ledwi
thnon-
zer
oval
uesandr
emai
ningspaces
ofmat
ri
xar
efi
l
ledwi
thzer
o.Thatmeans,
tot
all
yweal
l
ocat
e100x100x2=20,
000by
tesofspace
t
ost
oret
hisi
ntegermat
ri
x.Andt
oaccesst
hese10non-
zer
oel
ement
swehav
etomakescanni
ng
f
or10,
000t
imes.
Ther
ear
etwot
ypesofspar
semat
ri
ces.I
nthef
ir
stt
ypeofspar
semat
ri
x,al
lel
ement
sabov
e
t
hemai
ndi
agonalhav
eazer
oval
ue.Thi
sty
peofspar
semat
ri
xisal
socal
l
edal
owert
ri
angul
ar
mat
ri
xbecausei
fweseei
tpi
ctor
ial
l
y,al
ltheel
ement
swi
thanon-
zer
oval
ueappearbel
ow t
he
di
agonal
.
I
nal
owert
ri
angl
emat
ri
x,Ai,
j=0wher
ei<j
.Annxnl
owert
ri
angl
emat
ri
xAhasonenon-
zer
o
el
ementi
nthef
ir
str
ow,t
wonon-
zer
oel
ement
s,i
nthesecondr
ow andl
i
kewi
se,nnon-
zer
o
el
ement
si henthr
nt ow.

[ ]
1
5 3
2 7 -
1
3 1 4 2
9 2 -
- 8 1 7
Li
keal
owert
ri
angl
emat
ri
x,weal
sohav
eanupperr
ect
angl
emat
ri
xinwhi
chAi,
=0wher
j ei>j
.
Annxnuppert
ri
angl
emat
ri
xAhasnnon-
zer
oel
ement
sint
hef
ir
str
ow,
n-1non-
zer
oel
ement
sin
t
hesecondr
owandl
i
kewi
se,
1non-
zer
oel
ementi
nthenthr
ow.
[]
Inthesecondv ar
iantofasparsemat
rix,el
ementswithanon-
zer
oval
uecanappearonl
yon
t
hedi agonalorimmedi at
elyabov
eorbelow thediagonal
.Thi
stypeofmat
ri
xisalsocall
eda
t
ri
diagonalmatr
ix.
10

[ ]
4 1
5 1 2 1
9 3
2 2
4 5 1 9
8 7
Ar
rayRepr
esent
ati
onofSpar
seMat
ri
ces
Letusseehowwecanr
epr
esentaspar
semat
ri
x.Consi
dert
hespar
semat
ri
xgi
venbel
ow.

[ ]
0 2 0
0 0 4
0 0 0
Outof9 element
s,thematr
ixhasonl
ytwo non-
zer
o el
ement
s.Thi
sspar
semat
ri
xcan be
r
epresent
edusi
ngthemat
ri
xgi
venbel
ow.

[ ]
3 3 2
0 1 2
1 2 4
 Thef
ir
str
ow gi
vest
henumberofr
ows(
3),numberofcol
umns(
3),andnumberofnon-
zer
o
el
ement
s(2)i
nthespar
semat
ri
x.

 Thesecondr
ow speci
fi
est
hel
ocat
ionandv
alueoff
ir
stnon-
zer
oel
ement
.Thef
ir
stnon-
zer
o
v
alue2i
sat(
0,1)l
ocat
ion.

 Si
mil
arl
y,t
hir
drowspeci
fi
est
hel
ocat
ionandv
alueoft
henextnon-
zer
oel
ement
,i.
e.v
alue4at
(
1,2)l
ocat
ion.

Thismeansthatt
hearr
ayrepr
esent
ati
onoft
hespar
semat
ri
x,numberofr
owswi
l
lbeonemor
e
t
hanthenumberofnon-
zerov
alues.

i
mpor tjava.io.*;
cl
assSpar sityMat ri
x
{
publi
cst aticv oidmai n(Stri
ngar gs[])
{
Buf feredReaderi n=newBuf fer
edReader(
newI nputSt
reamReader
(Sy
stem.
in)
);
System. out.printl
n("Enterthedi mensionsofthematri
x:");
i
ntr ow=I nteger.parseInt(i
n.readLine(
));
i
ntcol=I nteger .
parseInt(i
n.readLine()
);
i
nt[][
]mat=newi nt[row][
col];
i
ntzer os=0;
System. out.printl
n("Entertheel ementsofthematri
x:");
for
(inti=0; i
<row; i++)
{
for(
intj=0; j<col;j
++)
{
mat [i
][j
]=I nteger .
parseInt(i
n.r
eadLine(
));
if
(mat [
i][
j]==0)
{
zer os++;
}
11

}
}
 
i
f(
zeros>(
row*col)
/2)
{
Sy
stem.
out
.pri
ntl
n("
Themat
ri
xisasparsemat
ri
x")
;
}
el
se
{
Sy
stem.
out
.pri
ntl
n("
Themat
ri
xisnotaspar
sematri
x")
;
}
 }
}

Tr
ansposeofaSpar
seMat
ri
x:

Tr
ansposeMat
ri
x

Amat
ri
xismadeupofr
owsandcol
umns.Gi
venamat
ri
xwi
th3r
owsand3col
umns:
123
456
789

Af
tert
ransposey
ouhav
e:
147
258
369

Jav
aPr
ogr
am t
oDi
spl
ayTr
ansposeMat
ri
x

Ent
ert
heel
ement
sofar
rayasi
nput
.Weobt
aint
het
ransposeofgi
venmat
ri
xbyi
nter
changi
ngal
lther
owsand
col
umnsofamat
ri
xwi
tht
hehel
pofl
oops.

Her
eist
hesour
cecodeoft
he 
Jav
aPr
ogr
am 
to 
Displ
ay 
TransposeMat
ri
x.The 
Jav
apr
ogr
ams 
successf
ull

compi
l
ed
andr
unonaWi
ndowssy
stem.Thepr
ogr
am 
out
put
 i
sal
soshownbel
ow.
Thi
sisa 
Jav
aPr
ogr
am 
to 
Displ
ay 
TransposeMat
ri
x.

i
mpor tjava.uti
l.
Scanner;
publi
ccl assTranspose
{
publi
cst ati
cv oi
dmain(Str
ingargs[
])
{
i
nti,j;
System. out
.pri
ntl
n("
Entertot
alrowsandcol
umns:"
);
Scanners=newScanner (
System.i
n);
12

i
ntr ow=s. next Int()
;
i
ntcolumn=s. next I
nt ();
i
ntar r
ay[][
]=newi nt[row] [
column];
System.out.print l
n("Ent ermat r
ix:
")
;
for
(i=0; i<row; i++)
{
for(
j=0; j<col umn; j
++)
{
array [
i][j
]=s. nextInt()
;
Syst em. out .
pr i
nt("")
;
}
}
System.out.print l
n("Theabov emat ri
xbefor
eTransposeis"
);
for
(i=0; i<row; i++)
{
for(
j=0; j<col umn; j
++)
{
Syst em. out .
pr i
nt(arr
ay[i
][
j]
+""
);
}
System.out .printl
n( "");
}
System.out.print l
n("Theabov emat ri
xaft
erTransposei
s");
for
(i=0; i<col umn; i++)
{
for(
j=0; j<r ow; j
++)
{
System. out .
print(array[j
][
i]
+"");
}
System.out .printl
n( "");
}
}
}
Out
put
:
$javacTranspose.
java
$javaTranspose
 
Entert
otalrowsandcolumns:
33
Entermatri
x:
1
2
3
4
5
6
7
8
9
Theabov ematri
xbeforeTransposei
s
123
456
789
Theabov ematri
xafterTr
ansposeis
147
13

258
369

3.LI
NKEDLI
STS
Al
i
nkedl
i
sti
sal
i
nearcol
l
ect
ionofdat
ael
ement
s.Thesedat
ael
ement
sar
ecal
l
ednodes.
Li
nkedl
i
stsar
edat
ast
ruct
ureswhi
chcanbeusedt
oimpl
ementot
herdat
ast
ruct
ures.Thus,t
hey
actasbui
l
dingbl
ocksf
orot
herdat
ast
ruct
uressuchasst
acks,
queues,
andt
hei
rvar
iat
ions.
I
tisady
nami
cdat
ast
ruct
ure.Forev
erydat
ael
ementi
nal
i
nkedl
i
st,t
her
eisanassoci
ated
poi
ntert
hatwoul
dgi
vet
hememor
ylocat
ionoft
henextdat
ael
ementi
nthel
i
nkedl
i
st.

Her
e,eachel
ementi
scal
l
edanodewhi
chhast
wopar
ts.

Info
address
 I
nfopar
twhi
chst
orest
hei
nfor
mat
ion
 Addr
essorpoi
nterpar
twhi
chhol
dst
headdr
essofnextel
ementofsamet
ype.
Thedat
ait
emsi
nthel
i
nkedl
i
star
enoti
nconsecut
ivememor
ylocat
ions.Theymaybe
any
wher
e,butt
heaccessi
ngoft
hesedat
ait
emsi
seasi
eraseachdat
ait
em cont
ainst
headdr
ess
oft
henextdat
ait
em.
Adv
ant
agesofl
i
nkedl
i
sts:
Li
nkedl
i
stsmayhav
eadv
ant
ages.Someofv
eryi
mpor
tantadv
ant
agesar
e:
1.Li
nkedl
i
stsar
edy
nami
cdat
ast
ruct
ures.i
.e.
,theycangr
oworshr
inkdur
ingt
heexecut
ionof
apr
ogr
am.
2.Li
nkedl
i
stshav
eef
fi
cientmemor
yut
il
izat
ion.Her
e,memor
yisnotpr
e-al
l
ocat
ed.Memor
yis
al
l
ocat
edwhenev
eri
tisr
equi
redandi
tisde-
all
ocat
ed(
remov
ed)wheni
tisnol
onger
needed.
14

3.I
nser
ti
onanddel
eti
onsar
eeasi
erandef
fi
cient
.Li
nkedl
i
stspr
ovi
def
lexi
bil
i
tyi
ninser
ti
nga
dat
ait
em ataspeci
fi
edposi
ti
onanddel
eti
onoft
hedat
ait
em f
rom t
hegi
venposi
ti
on.
4.Manycompl
exappl
i
cat
ionscanbeeasi
l
ycar
ri
edoutwi
thl
i
nkedl
i
sts.
Di
sadv
ant
agesofl
i
nkedl
i
sts:
1.I
tconsumesmor
espacebecauseev
erynoder
equi
resanaddi
ti
onal
poi
ntert
ost
oreaddr
ess
oft
henextnode.
2.Sear
chi
ngapar
ti
cul
arel
ementi
nli
sti
sdi
ff
icul
tandal
sot
imeconsumi
ng.
Ty
pesofLi
nkedLi
sts:
1.Si
ngl
eLi
nkedLi
st
2.Doubl
eLi
nkedLi
st
3.Ci
rcul
arLi
nkedLi
st
4.Ci
rcul
arDoubl
eLi
nkedLi
st.
Asi
ngl
eli
nkedl
i
sti
sonei
nwhi
chal
lnodesar
eli
nkedt
oget
heri
nsomesequent
ialmanner
.
Hencei
tisal
socal
l
edl
i
nearl
i
nkedl
i
st.
Adoubl
eli
nkedl
i
sti
sonei
nwhi
chal
lnodesar
eli
nkedt
oget
herbymul
ti
plel
i
nkswhi
chhel
psi
n
accessi
ngbot
hthesuccessornode(
nextnode)andpr
edecessornode(
prev
iousnode)f
rom any
ar
bit
rar
ynodewi
thi
nthel
i
st.Ther
efor
eeachnodei
nadoubl
eli
nkedl
i
sthast
wol
i
nkf
iel
ds
(
poi
nter
s)t
opoi
ntt
othel
eftnode(
prev
ious)andt
her
ightnode(
next
).Thi
shel
pst
otr
aver
sei
n
f
orwar
ddi
rect
ionandbackwar
ddi
rect
ion.
Aci
rcul
arl
i
nkedl
i
sti
sone,whi
chhasnobegi
nni
ngandnoend.Asi
ngl
eli
nkedl
i
stcanbe
madeaci
rcul
arl
i
nkedl
i
stbysi
mpl
yst
ori
ngaddr
essoft
hef
ir
stnodei
sthel
i
nkf
iel
doft
hel
ast
node.
Aci
rcul
ardoubl
eli
nkedl
i
sti
sone,whi
chhasbot
hthesuccessorpoi
nterandpr
edecessor
poi
nteri
ntheci
rcul
armanner
.
Ar
ray
sVsLi
nkedLi
sts:
Li
nkedl
i
stsandar
ray
sar
esi
mil
arsi
ncet
heybot
hst
orecol
l
ect
ionsofdat
a.Ar
rayi
sthemost
commondat
ast
ruct
ureusedt
ost
orecol
l
ect
ionsofel
ement
s.Ar
ray
sar
econv
eni
entt
odecl
are
andpr
ovi
det
heeasysy
ntaxt
oaccessanyel
ementbyi
tsi
ndexnumber
.Oncet
hear
rayi
ssetup,
accesst
oanyel
ementi
sconv
eni
entandf
ast
.
Li
nkedl
i
stshav
ethei
rownst
rengt
hsandweakness,
butt
heyhappent
obest
rongwher
ear
ray
s
ar
eweak.Gener
all
yar
ray
’sal
l
ocat
est
hememor
yforal
lit
sel
ement
sinonebl
ockwher
easl
i
nked
l
i
stsuseanent
ir
elydi
ff
erentst
rat
egy
.Li
nkedl
i
stsal
l
ocat
ememor
yforeachel
ementsepar
atel
y
andonl
ywhennecessar
y.
15

ARRAY LI
NKEDLI
ST
Si
zeofanar
rayi
sfi
xed Si
zeofal
i
sti
snotf
ixed
Memor
yisal
l
ocat
edf
rom st
ack Memor
yisal
l
ocat
edf
rom heap
I
tisnecessar
ytospeci
fyt
henumberof I
tisnotnecessar
ytospeci
fyt
henumberof
el
ement
s dur
ing decl
arat
ion (
i.
e.,dur
ing el
ement
sdur
ing decl
arat
ion(
i.
e.,memor
yis
compi
l
eti
me)
. al
l
ocat
eddur
ingr
unt
ime)
.
I
toccupi
esl
essmemor
ythanal
i
nked I
toccupi
esmor
ememor
y.
l
i
stf
ort
hesamenumberofel
ement
s.
I
nser
ti
ng new el
ement
s at t
he f
ront i
s I
nser
ti
nganewel
ementatanyposi
ti
on
pot
ent
ial
ly expensi
ve because exi
sti
ng canbecar
ri
edouteasi
l
y.
el
ementsneedtobeshift
edov ert
omake
r
oom.
Del
eti
nganel
ementf
rom anar
rayi
s Del
eti
nganel
ementi
spossi
ble.
notpossi
ble.

SI
NGLELI
NKEDLI
ST
Asi
ngl
yli
nkedl
i
st,orone-
wayl
i
st,i
sal
i
nearcol
l
ect
ionofdat
ael
ement
s,cal
l
ednodes,wher
e
t
hel
i
nearor
deri
sgi
venbymeansofpoi
nter
s.Thati
s,eachnodei
sdi
vi
dedi
ntot
wopar
ts:t
hef
ir
st
par
tcont
ainst
hei
nfor
mat
ionoft
heel
ement
,andt
hesecondpar
t,cal
l hel
edt i
nkf
iel
dornext
poi
nterf
iel
d,cont
ainst
headdr
essoft
henextnodei
nthel
i
st.
START

1 2 3 4 5 6 7x

Asi
ngl
yli
nkedl
i
stal
l
owst
rav
ersal
ofdat
aonl
yinonedi
rect
ion.
Tr
aver
singaSi
ngl
yLi
nkedLi
st:
Tr
aver
singal
i
nkedl
i
stmeansaccessi
ngt
henodesoft
hel
i
sti
nor
dert
oper
for
m some
oper
ati
onsont
hem.Al
i
nkedl
i
stal
way
scont
ainsapoi
nterv
ari
abl
est
artwhi
chst
orest
headdr
ess
oft
hef
ir
stnodeoft
hel
i
st.Theendoft
hel
i
sti
smar
kedbyst
ori
ngNULLor-
1int
heNEXTf
iel
dof
t
hel
astnode.Theal
gor
it
hm t
otr
aver
seal
i
nkedl
i
sti
sshownbel
ow.
St
ep1.[I
NITIALI
ZATI ON]SetPTR=START
St
ep2 Repeatsteps3and4Whi lePTR!
=NULL
St
ep3. ApplyprocesstoPTR->DATA
St
ep4. PTR=PTR- >NEXT
[
EndofWhi leLoop]
16

St
ep5.Exi
t
I
nthi
sal
gor
it
hm,wef
ir
sti
nit
ial
i
zePTRwi
tht
headdr
essofSTART.SonowPTRpoi
ntst
othe
f
ir
stnodeoft
hel
i
nkedl
i
st.Theni
nSt
ep2,awhi
l
eloopi
sexecut
edwhi
chi
srepeat
edt
il
lPTR
pr
ocessest
hel
astnode.I
nSt
ep3,weappl
ythepr
ocess(
e.g.
,pr
int
)tot
hecur
rentnode,i
.e.
,the
nodepoi
ntedbyPTR.I
nSt
ep4,
wemov
etot
henextnodebymaki
ngPTRpoi
ntt
othenodewhose
addr
essi
sst
oredi
ntheNEXTf
iel
d.
Sear
chi
ngf
orav
aluei
naLi
nkedLi
st:
Sear
chi
ngl
i
nkedl
i
stmeanst
ofi
ndapar
ti
cul
arel
ementi
nthel
i
nkedl
i
st.I
nsear
chi
ngpr
ocess
f
indi
ngwhet
heragi
venv
aluei
spr
esenti
ntheDATApar
toft
henodeornot
.Ifi
tispr
esent
,the
sear
chal
gor
it
hm r
etur
nst
headdr
essoft
henodet
hatcont
ainst
hatv
alue.
St
ep1.[I
NITIALI
ZATION]SetPTR=START
St
ep2 Repeatsteps3Whi l
ePTR!=NULL
St
ep3. I
fVAL=PTR- >DATA
SetPOS=PTR
Got oSt ep5
Else
SetPTR=PTR- >NEXT
[EndofI F]
[
EndofWhi l
eLoop]
St
ep4.SetPOS=NULL
St
ep5.Exit
I
nSt
ep1,wei
nit
ial
i
zeapoi
nterv
ari
abl
ePTRwi
thSTART.I
nSt
ep2,awhi
l
eloopi
sexecut
ed
whi
chwi
l
lcompar
eev
erynode’
sDATAwi
thVALf
orwhi
cht
hesear
chi
sbei
ngmade.I
fsear
chi
s
successf
ul,t
hati
s,VALhasbeenf
ound,t
hent
headdr
essoft
henodei
sst
oredi
nPOSandt
he
cont
rolj
umpt
othel
astst
atementoft
heal
gor
it
hm.Howev
er,
ift
hesear
chi
sunsuccessf
ul,
POSi
s
sett
oNULL,
whi
chi
ndi
cat
est
hatVALi
snotpr
esenti
nthel
i
nkedl
i
st.
I
nser
ti
ngaNewNodei
naLi
nkedLi
st:
I
nser
ti
nganewnodei
ntot
hel
i
sthast
hreecases.
Case1:
Thenewnodei
sinser
tedatt
hebegi
nni
ngofal
i
nkedl
i
st
Case2:
Thenewnodei
sinser
tedatt
heendofal
i
nkedl
i
st
Case3:
Thenewnodei
sinser
tedatt
hemi
ddl
eofal
i
nkedl
i
st
Case1:I
nser
ti
ngnewnodeatt
hebegi
nni
ngofal
i
nkedl
i
st:
St
ep1:I
fAVAI L=NULL,then
Wri
teOVERFLOW
GotoStep7
[EndofI
f]
St
ep2:SetNew_Node=AVAI L
St
ep3:SetAVAIL=AVAI L-
>NEXT
St
ep4:SetNew_Node->DATA=VAL
St
ep5:SetNew_Node->Next=START
17

St
ep6:SetSTART=New_
Node
St
ep7:Exi
t
I
ntheabov
eal
gor
it
hm i
susedt
oinser
tanewnodeatt
hebegi
nni
ngofal
i
nkedl
i
st.I
nSt
ep1,
wef
ir
stcheckwhet
hermemor
yisav
ail
abl
efort
henew node.I
fthef
reememor
yhasbeen
exhaust
edt
henanOVERFLOW messagei
spr
int
ed.Ot
her
wise,i
saf
reememor
ycel
lisav
ail
abl
e
t
henweal
l
ocat
espacef
ort
henewnode.I
tsDATApar
tissetwi
tht
hegi
venVALandi
tsNEXTpar
t
i
sini
ti
ali
zedwi
tht
headdr
essoft
hef
ir
stnodeoft
hel
i
st,whi
chi
sst
oredi
nSTART.I
nSt
ep6,t
he
STARTpoi
nterv
ari
abl
ewi
l
lnow hol
dtheaddr
essoft
heNew_
Node.St
ep2&3st
epsal
l
ocat
e
memor
yfort
henewnode.
Case2:I
nser
ti
ngnewnodeatt
heendofal
i
nkedl
i
st:
St
ep1:IfAVAI L=NULL, t
hen
Writ
eOVERFLOW
GotoStep10
[EndofIf]
St
ep2:SetNew_ Node=AVAI L
St
ep3:SetAVAI L=AVAI L->NEXT
St
ep4:SetNew_ Node-
>DATA=VAL
St
ep5:SetNew_ Node-
>Next =NULL
St
ep6:SetPTR=START
St
ep7:RepeatSt ep8Whi l
ePTR- >NEXT!
=NULL
St
ep8: SetPTR=PTR- >NEXT
[EndofLoop]
St
ep9:SetPTR- >NEXT=New_ Node
St
ep10:Exi
t
I
nabov
eal
gor
it
hm,i
nst
ep6,wet
akeapoi
nterPTRandi
nit
ial
i
zei
twi
thSTART.Thati
s,PTR
nowpoi
ntst
othef
ir
stnodeoft
hel
i
nkedl
i
st.I
nthewhi
l
eloop,wet
rav
erset
hrought
hel
i
nkedl
i
st
t
oreacht
hel
astnode.Oncewer
eacht
hel
astnode,
inSt
ep9,
wechanget
heNEXTpoi
nteroft
he
l
astnodet
ost
oret
headdr
essoft
henew node.TheNEXTf
iel
doft
henew nodecont
ainsNULL
whi
chsi
gni
fi
est
heendoft
hel
i
nkedl
i
st.
Case3:I
nser
ti
ngnewnodeatt
hemi
ddl
eofal
i
nkedl
i
st:
St
ep1:I
fAVAI L=NULL,then
Writ
eOVERFLOW
GotoStep12
[EndofIf]
St
ep2:SetNew_Node=AVAI L
St
ep3:SetAVAIL=AVAI L-
>NEXT
St
ep4:SetNew_Node->DATA=VAL
St
ep5:SetPTR=START
St
ep6:SetPREPTR=PTR
St
ep7:RepeatStep8and9Whi l
ePTR-
>NEXT!
=NUM
18

St
ep8: SetPREPTR=PTR
St
ep9: SetPTR=PTR->NEXT
[EndofLoop]
St
ep10:PREPTR->NEXT=New_ Node
St
ep11:SetNew_Node->NEXT=PTR
St
ep10:Exi
t
I
ntheabov
eal
gor
it
hm,i
nst
ep5,wet
akeapoi
nterPTRandi
nit
ial
i
zei
twi
thSTART.Thati
s,
PTRnowpoi
ntst
othef
ir
stnodeoft
hel
i
nkedl
i
st.Thenwet
akeanot
herpoi
nterv
ari
abl
ePREPTR
whi
chwi
l
lbeusedt
ost
oret
headdr
essoft
henodepr
ecedi
ngPTR.I
nit
ial
l
y,PREPTRi
sini
ti
ali
zedt
o
PTR.Sonow,
PTR,
PREPTR,
andSTARTal
lpoi
ntt
othef
ir
stnodeoft
hel
i
nkedl
i
st.
I
nthewhi
l
eloop,
wet
rav
erset
hrought
hel
i
nkedl
i
stt
oreacht
henodet
hathasi
tsv
alueequal
t
oNUM.Oncewer
eacht
hisnode,
inSt
eps10and11,
wechanget
heNEXTpoi
nter
sinsuchaway
t
hatanewnodei
sinser
tedaf
tert
hedesi
rednode.
Del
eti
ngaNewNodei
naLi
nkedLi
st:
Del
eti
nganewnodei
ntot
hel
i
sthast
hreecases.
Case1:
Thef
ir
stnodei
sdel
eted
Case2:
Thesecondnodei
sdel
eted
Case3:
Thenodeaf
tert
hegi
vennodei
sdel
eted.

Case1:Thef
ir
stnodei
sdel
eted
St
ep1:I
fSTART=NULL, t
hen
Writ
eUNDERFLOW
GotoStep5
[
EndofIf]
St
ep2:SetPTR=Start
St
ep3:SetSTART=START- >NEXT
St
ep4:FreePTR
St
ep5:Exit
I
nSt
ep1oft
heal
gor
it
hm,wechecki
fthel
i
nkedl
i
stexi
sts.I
fSTART=NULL,t
heni
tsi
gni
fi
es
t
hatt
her
ear
enonodesi
nthel
i
standt
hecont
roli
str
ansf
err
edt
othel
astst
atementoft
he
al
gor
it
hm.
I
fther
ear
enodesi
nthel
i
nkedl
i
st,
thenweuseapoi
nterv
ari
abl
ePTRt
hati
ssett
opoi
ntt
othe
f
ir
stnodeoft
hel
i
st.Fort
his,wei
nit
ial
i
zePTRwi
thSTARTwhi
chst
orest
headdr
essoft
hef
ir
st
nodeoft
hel
i
st.I
nSt
ep3,STARTi
smadet
opoi
ntt
othenextnodei
ssequenceandf
inal
l
ythe
memor
yoccupi
edbyt
henodepoi
ntedbyPTRi
sfr
eed.
Case2:Thel
astnodei
sdel
eted
St
ep1:I
fSTART=NULL,then
Wri
teUNDERFLOW
GotoSt
ep8
19

[
EndofIf]
St
ep2:SetPTR=Start
St
ep3:RepeatSteps4and5whi l
ePTR-
>NEXT!
=NULL
St
ep4: SetPREPTR=PTR
St
ep5: SetPTR=PTR->NEXT
[
Endofloop]
St
ep6:SetPREPTR->NEXT=NULL
St
ep7:FreePTR
St
ep8:Exit
I
nSt
ep2,wet
akeapoi
nterv
ari
abl
ePTRandi
nit
ial
i
zei
ttoSTART.Thati
s,PTRnowpoi
ntst
o
t
hef
ir
stnodeoft
hel
i
nkedl
i
st.I
nthewhi
l
eloop,wet
akeanot
herpoi
nteranot
herpoi
nterv
ari
abl
e
PREPTRsucht
hati
sal
way
spoi
ntst
oonenodebef
orePTR.Oncewer
eacht
hel
astandt
he
secondl
astnodes,wesett
heNEXTpoi
nteroft
hesecondl
astnodet
oNULL.Thememor
yoft
he
i
nit
ial
lastnodei
sfr
eed.
Case3:Thenodeaf
tergi
vennodei
sdel
eted
St
ep1:IfSTART=NULL, then
Writ
eUNDERFLOW
GotoStep8
[
EndofIf]
St
ep2:SetPTR=St art
St
ep3:SetPREPTR=PTR
St
ep4:RepeatSt eps5and6whi l
ePTR->NEXT!
=NUM
St
ep5: SetPREPTR=PTR
St
ep6: SetPTR=PTR->NEXT
[
Endofloop]
St
ep7:SetTEMP=PTR
St
ep8:SetPREPTR- >NEXT=PTR->NEXT
St
ep9:Fr eePTR
St
ep10:Exit
I
nSt
ep2,
wet
akeapoi
nterv
ari
abl
ePTRandi
nit
ial
i
zei
ntoSTART.Thati
s,PTRnowpoi
ntst
o
t
hef
ir
stnodeoft
hel
i
nkedl
i
st.I
nthewhi
l
eloop,wet
akeanot
herpoi
nterv
ari
abl
ePREPTRsuch
t
hati
tal
way
spoi
ntst
oonenodebef
orePTR.Oncewer
eacht
henodecont
aini
ngNUM andt
he
nodesucceedi
ngi
t,wesett
heNEXTpoi
nteroft
henodecont
aini
ngNUM t
otheaddr
esscont
ained
i
nNEXTf
iel
doft
henodesucceedi
ngi
t.Thememor
yoft
henodesucceedi
ngt
hegi
vennodei
s
f
reed.

Cr
eat
eaLi
nkedLi
standi
nser
tnodesatst
artoft
hel
i
st
cl
assNode{
publ
ici
ntdat
a;
publ
icNodenext
;
20

publ
icvoiddispl
ayNodeDat
a(){
System.out.
pri
ntl
n("
["+data+"]"
);
}
}

cl
assSinglyLi
nkedLi
st{
pri
vateNodehead;
publi
cv oi
dinsert
Fir
st(
intdat
a)
{
NodenewNode=newNode( )
;
newNode.data=data;
newNode.next=head;
head=newNode;
}

publ
icv
oidpri
ntLinkedLi st(
){
Syst
em. out .
printl
n("Pri
nti
ngLi
nkedLi
st(
head-
->l
ast
)")
;
Nodecur rent=head;
whil
e(cur rent!=nul l
)
{
current .
displayNodeData(
);
current=cur rent.
next;
}
Syst
em. out .
printl
n();
}
}

publ
iccl
assLi
nkedLi
stMai
n{

publ
icstaticvoi dmai n(Stringargs[]
)
{
SinglyLinkedListmy Linkedli
st=newSi
ngl
yLi
nkedLi
st(
);
my Linkedlist.
insertFirst(
5);
my Linkedlist.
insertFirst(
6);
my Linkedlist.
insertFirst(
7);
my Linkedlist.
insertFirst(
1);
my Linkedlist.
printLinkedList(
);
}
}
21

DOUBLELI
NKEDLI
ST
Adoubl
eli
nkedl
i
stort
wo-
wayl
i
nkedl
i
sti
samor
ecompl
ext
ypeofl
i
nkedl
i
stwhi
chcont
ainsa
poi
ntert
othenextaswel
last
hepr
evi
ousnodei
nsequence.Ther
efor
e,i
tconsi
stsoft
hreepar
ts–
dat
a,apoi
ntert
othenextnode,
andapoi
ntert
othepr
evi
ousnode.

Fol
l
owi
ngar
ethebasi
coper
ati
on

Thepr evfiel
dofthefir
stnodeandt henextfiel
doft helastnodecont ainNULL.Theprevfiel
dis
usedtost oretheaddressofthepr ecedingnode.Thi swoul denabl
eonet otraver
sethelistinthe
backwarddirecti
onaswel l
.
Thus, weseet hatadoublyli
nkedl i
stcallsformor espacepernodeandmor eexpensivebasic
operat
ions.Howev eradoublylinkedlistprovidestheeaset omani pul
at etheelementsoft heli
st
asitmai ntainspointer
st o nodesi nbot ht hedi r
ections(forward and backward).Themai n
advant
ageofusi ngdoublyli
nkedl i
stisthatitmakessear chtwiceasefficient
.

Memor
yrepr
esentat
ionofadoubl
yli
nkedli
st:
Memoryrepr
esentat
ionofadoubl
yli
nkedli
sti
sshowni
nthef
oll
owi
ngi
mage.

DATA PREV NEXT


1 H -1 3
2
3 E 1 7
4
5
6
7 L 3 8
8 L 7 10
9
10 O 8 -
1

I
ntheabov
efi
gur
e,weseet
hatav
ari
abl
eSTARTi
susedt
ost
oret
headdr
essoft
hef
ir
stnode.
22

Herei nthi
sexample,START=1,sot hefir
stdataisstoredataddress1,whi
chis‘H’
.Si
ncethi
sis
thef i
rstnode,i
thasnopr eviousnodeandhencest oresNULLor- 1int hePREV f
iel
d.The
correspondi
ngNEXTst or
estheaddr essoft henextnode,whichi
s3.
Insert
ion:
Anodecanbeaddedi n3way s
1: Att hefr
ontoftheDoubleLinkedLi st
2: Att heendoftheDoubleLinkedLi st
3: Att hemiddl
eoftheDoubleLi nkedList

1:Att
hef
rontoft
heDoubl
eLi
nkedLi
st
Wewanttoaddanew nodewit
hdat
a9ast
hef
ir
stnodeoft
hel
i
st.Thent
hef
oll
owi
ng
changeswi
l
lbedonei
nthel
i
nkedli
st.

X 1 7 3 4X
START
Al
l
ocat
ememor
yfort
henewnodeandi
nit
ial
i
zei
tsDATApar
tto9andPREVf
iel
dtoNULL
X 9
Addt
henewnodebef
oret
heSTARTnode.Nowt
henewnodebecomest
hef
ir
stnodeoft
hel
i
st.

X 9 1 7 3 4X

St
ep1:Begin
St
ep2:I
fAVAI L=NULL, then
Writ
eOVERFLOW
GotoSt ep9
[
EndofIf]
St
ep3:CreateaNew_ Node
St
ep4:SetNew_Node- >DATA=VAL
St
ep5:SetNew_Node- >PREV=NULL
St
ep6:SetNew_Node- >Next=START
St
ep7:SetSTART->PREV=New_ Node
St
ep8:SetSTART=New_ Node
St
ep9:Exit
I
ntheabov
eal
gor
it
hm i
susedt
oinser
tanewnodeatt
hebegi
nni
ngofal
i
nkedl
i
st.I
nSt
ep2,
wef
ir
stcheckwhet
hermemor
yisav
ail
abl
efort
henew node.I
fthef
reememor
yhasbeen
exhaust
edt
henanOVERFLOW messagei
spr
int
ed.Ot
her
wise,i
saf
reememor
ycel
lisav
ail
abl
e
t
henweal
l
ocat
espacef
ort
henewnode.I
tsDATApar
tissetwi
tht
hegi
venVALandi
tsNEXTpar
t
i
sini
ti
ali
zedwi
tht
headdr
essoft
hef
ir
stnodeoft
hel
i
st,whi
chi
sst
oredi
nSTART.I
nSt
ep6,t
he
STARTpoi
nterv
ari
abl
ewi
l
lnowhol
dtheaddr
essoft
heNew_
Node.

2:Att
heendoft
heDoubl
eLi
nkedLi
st
Wewantt
oaddanewnodewi
thdat
a9ast
hel
astnodeoft
hel
i
st.Thent
hef
oll
owi
ngchanges
23

wi
l
lbedonei
nthel
i
nkedl
i
st.

X 1 7 3 4X

START
Al
locat
ememoryfort
henewnodeandi
nit
ial
izei
tsDATApar
tto9andi
tsNEXTt
oNULL
9X
Takeapoi
nterv
ari
abl
ePTRandmakei
tpoi
ntt
othef
ir
stnodeoft
hel
ist
.

X 1 7 3 4X
START,PTR
Mov
ePTRsot
hatitpoi
ntst
othel
astnodeoft
hel
ist
.Addt
henewnodeaf
tert
henodepoi
ntedbyPTR.

X 1 7 3 4X 9X

START PTR

St
ep1:Begi n
St
ep2:IfAVAI L=NULL, then
Writ
eOVERFLOW
GotoSt ep11
[
EndofIf]
St
ep3:Cr eateaNew_ Node
St
ep4:SetNew_ Node->DATA=VAL
St
ep5:SetNew_ Node->Next=NULL
St
ep6:SetPTR=START
St
ep7:RepeatSt ep8Whi lePTR->NEXT!
=NULL
St
ep8: SetPTR=PTR->NEXT
[
EndofLoop]
St
ep9:SetPTR- >NEXT=New_ Node
St
ep10:New_ Node-
>PREV=PTR- >NEXT
St
ep11:Exit

Intheaboveal
gori
thm,i
nstep6,
wet akeapoint
ervari
abl
esPTRandi ni
ti
ali
zeitwit
hSTART.In
thewhilel
oop,wetrav
ersethr
oughtheli
nkedli
sttoreachthelastnode.Oncewer eacht
helast
node,i
nstep9,wechangetheNEXTpointeroft
helastnodetostor
etheaddressofthenewnode.
TheNEXTf i
eldoft
henewnodecontainsNULLwhichsigni
fi
estheendoftheli
st.
3:Att
hemi
ddl
eoft
heDoubl
eLi
nkedLi
st
St
ep1:Begi
n
St
ep2:I
fAVAI
L=NULL,
then
Wr
it
eOVERFLOW
Got
oSt
ep9
[
EndofI
f]
St
ep3:Cr
eat
eaNew_
Node
24

St
ep4:SetNew_
Node-
>DATA=VAL
St
ep5:SetPTR=START
St
ep6:RepeatSt
ep7Whi
lePTR-
>DATA!
=NUM
St
ep7: SetPREPTR=PTR
St
ep8: SetPTR=PTR-
>NEXT
[
EndofLoop]
St
ep9:SetNew_
Node-
>NEXT=PTR
St
ep10:SetNew_
Node-
>PREV=PREPTR-
>NEXT
St
ep10:SetPTR-
>PREV=New_
Node
St
ep11:SetPREPTR-
>NEXT=New_
Node
St
ep12:Exi
t

InStep2,wef irstcheckwhet hermemor yi


sav ai
l
abl
eforthenewnode.I nstep5,wet akea
poi
ntervari
ablePTRi ni
ti
ali
zeitwithSTART.Thatis,PTRnowpointstothefi
rstnodeofthelinked
l
ist
.Inthewhileloop,wet r
aversethroughtheli
nkedli
stt
oreachthenodethathasitsval
ueequal
toNUM.Oncewer eacht hi
snode, wechangetheNEXTandPREVf iel
dsi
nsuchawayt hatt
henew
nodeisinser
tedbeforethedesirednode.
Del
eti
ngaNodef
rom aDoubl
yLi
nkedLi
st:
Case1:TheFi
rstnodei
sdel
eted
Whenwewanttodelet
eanodef
rom t
hebegi
nni
ngoft
hel
i
st,t
hent
hef
oll
owi
ngchangeswi
l
l
bedonei
nthel
i
nkedli
st.
St
ep1:Begi
n
St
ep2:i
fSTART=NULL
Wr
it
eUNDERFLOW
Got
oSt
ep7
[
Endofi
f]
St
ep3:SetPTR=START
St
ep4:SetSTART=START-
>NEXT
St
ep5:SetSTART-
>PREV=NULL
St
ep6:Fr
eePTR
St
ep7:Exi
t
I
ntheabov eal
gor
it
hm,i
nStep1,wecheckift
heli
nkedli
stexi
stsornot.I
fSTART=NULL,then
i
tissi
gnif
iesthatt
her
earenonodesi
ntheli
standthecont
roli
stransf
err
edtothelastst
atement
oft
healgori
thm.
I
ftherearenodesintheli
nkedlist
,thenweuseat emporarypoint
erv ar
iabl
ePTRt hatthatis
sett
opointtothefi
rstnodeoftheli
nkedli
st.Forthi
s,weini
ti
ali
zePTRwi t
hSTARTt hatstor
est he
addr
essofthefir
stnodeoftheli
st.I
nstep3, STARTismadet opointtothenextnodeinsequence
andfi
nal
lythememor yoccupi
edbyPTR.
25

Case2:Del
eti
ngt
heLastNodef
rom aDoubl
yLi
nkedLi
st
St
ep1:Begi
n
St
ep2:i
fSTART=NULL
Wr
it
eUNDERFLOW
Got
oSt
ep7
[
Endofi
f]
St
ep3:SetPTR=START
St
ep4:Repeatst
ep5whi
lePTR-
>NEXT!
=NULL
St
ep5: SetPTR=PTR-
>NEXT
[
endofl
oop]
St
ep6:SetTEMP=PTR
St
ep7:SetPTR=NULL,
PTR-
>PREV=NULL
St
ep8:Fr
eeTEMP
St
ep9:Exi
t
26

Cr
eat
ingDoubl
eLi
nkedLi
st:

publi
ccl assDLL{
 
  
 Nodehead;   
 
  
 cl
assNode{
 
  
  
  
 i
ntdat a;
 
  
  
  
 Nodepr ev;
 
  
  
  
 Nodenext ;
 
  
  
  
 Node( i
ntd){
data=d;
}
 
  
 }
}
publi
cv oidpush(intnew_dat
a)
{
 
  
 Nodenew_ Node=newNode( new_
dat
a);
 
  
 new_Node. next=head;
 
  
 new_Node. prev=null
;
 
  
 i
f(head! =null)
 
  
  
  
 head.prev=new_ Node;
 
  
 head=new_ Node;}
CI
RCULARLI
NKEDLI
ST
I
naci
rcul
arl
i
nkedl
i
st,
thel
astnodecont
ainsapoi
ntert
othef
ir
stnodeoft
hel
i
st.Wecanhav
e
aci
rcul
arsi
ngl
yli
nkedl
i
staswel
lasci
rcul
ardoubl
yli
nkedl
i
st.Whi
l
etr
aver
singaci
rcul
arl
i
nkedl
i
st,
wecanbegi
natanynodeandt
rav
erset
hel
i
sti
nanydi
rect
ion,
for
war
dorbackwar
d,unt
ilwer
each
t
hesamenodewher
ewest
art
ed.Thus,
aci
rcul
arl
i
nkedl
i
sthasnobegi
nni
ngandnoend.
START

1 2 3 4 5 6 7

Theonl
ydi
sadv
ant
ageofaci
rcul
arl
i
nkedl
i
sti
sthecompl
exi
tyofi
ter
ati
ons.Ci
rcul
arl
i
nked
l
i
stsar
ewi
del
yusedi
noper
ati
ngsy
stemsf
ort
askmai
ntenance.
Wecant
rav
erset
hel
i
stunt
ilwef
indt
heNEXTent
ryt
hatcont
ainst
headdr
essoft
hef
ir
stnode
oft
hel
i
st.Thi
sdenot
est
heendoft
hel
i
nkedl
i
st,
thati
s,t
henodet
hatcont
ainst
headdr
essoft
he
f
ir
stnodei
sact
ual
l
ythel
astnodeoft
hel
i
st.
I
nsert
ingaNewNodeinaCircul
arLinkedLi
st:
Wewill
taket
wocasesandt henseehowinser
ti
onisdonei neachcase.
Case1:Thenewnodei
sinsert
edatthebeginni
ngofthecir
cularl
inkedl
ist
Case2:Thenewnodei
sinsert
edattheendofthecir
cularl
inkedli
st.

I
nser
ti
ngaNodeatt
heBegi
nni
ngofaCi
rcul
arLi
nkedLi
st
St
ep1:Begi
n
St
ep2:I
fAVAIL=NULL,
then
27

Writ
eOVERFLOW
GotoSt ep11
[
EndofIf]
St
ep3:Cr eateaNew_ Node
St
ep4:SetNew_ Node- >DATA=VAL
St
ep5:SetPTR=START
St
ep6:RepeatSt ep7whi l
ePTR->NEXT!
=START
St
ep7: PTR=PTR- >NEXT
[
Endofloop]
St
ep8:SetNew_ Node- >NEXT=START
St
ep9:SetPTR- >NEXT=New_ Node
St
ep10:SetSTART=New_ Node
St
ep11:Stop

I
ntheabov
eal
gor
it
hm,
inst
ep1,
wef
ir
stcheckwhet
hermemor
yisav
ail
abl
efort
henewnode.
I
fthef
reememor
yhasexhaust
ed,t
henanov
erf
low messagei
spr
int
ed.Ot
her
wise,t
henwe
al
l
ocat
espacef
ort
henew node.Seti
tsDATA par
twi
tht
hegi
venVALandt
heNEXTpar
tis
i
nit
ial
i
zedwi
tht
headdr
essoft
hef
ir
stoft
hel
i
st,i
twi
l
lnowbeknownast
heSTARTnode,t
hati
s
t
heSTARTpoi
nterv
ari
abl
ewi
l
lnowhol
dtheaddr
essoft
henew_
node.
I
nser
ti
ngaNodeatt
heEndofaCi
rcul
arLi
nkedLi
st
St
ep1:Begin
St
ep2:IfAVAIL=NULL, then
Writ
eOVERFLOW
GotoSt ep10
[
EndofIf]
St
ep3:CreateaNew_ Node
St
ep4:SetNew_Node- >DATA=VAL
St
ep5:SetNew_Node- >NEXT=START
St
ep6:SetPTR=START
St
ep7:RepeatStep8whi lePTR-
>NEXT!
=START
St
ep8: PTR=PTR- >NEXT
[
Endofloop]
St
ep9:SetPTR->NEXT=New_ Node
St
ep10:St
op
I
ntheabov
eal
gor
it
hm,I
nst
ep6,wet
akeapoi
nterv
ari
abl
ePTRandi
nit
ial
i
zei
twi
thSTART.
Thati
s,PTRnowpoi
ntst
othef
ir
stnodeoft
hel
i
nkedl
i
st.I
nthewhi
l
eloop,
wet
rav
erset
hrought
he
l
i
nkedl
i
stt
oreacht
hel
astnode.I
nst
ep9,wechanget
heNEXTpoi
nteroft
hel
astnodet
ost
ore
t
headdr
essoft
henew node.TheNEXTf
iel
doft
henew nodecont
ainst
headdr
essoft
hef
ir
st
nodewhi
chi
sdenot
edbySTART.

Del
eti
ngaNodef
rom aCi
rcul
arLi
nkedLi
st:
28

Case1:
Thef
ir
stnodei
sdel
eted
Case2:
Thel
astnodei
sdel
eted

Del
eti
ngt
heFi
rstNodef
rom aCi
rcul
arLi
nkedLi
st
St
ep1:Begin
St
ep2:IfSTART=NULL
Writ
eUNDERFLOW
GotoStep9
[
EndofIf]
St
ep3:SetPTR=START
St
ep4:RepeatStep5whil
ePTR->NEXT!=START
St
ep5: PTR=PTR- >NEXT
[
Endofloop]
St
ep6:SetPTR->NEXT=START- >NEXT
St
ep7:FREESTART
St
ep8:SetSTART=PTR- >NEXT
St
ep9:Stop

Intheabov eal gori


thm,inStep2wechecki fli
nedlistexistsornot .I
fSTART=NULL,t henit
si
gnifi
esthattherearenonodesi nt
helistandthecont
rolist
ransferredtothelaststep.
Iftherearenodesi nt heli
nkedlist
,thenweuseapoi nt
erv ari
ablePTRwhi chwi llbeusedt o
tr
aversethelisttoreachlastnode.Instep6,wechanget henextpoi nterofthelastnodet opoint
tothesecondnodeoft hecir
cularl
inkedlist
.Inst
ep7,thememor yoccupiedbyt hef i
rstnodeis
fr
eed.Finall
yinStep8.Thesecondnodenowbecomest hefirstnodeoft heli
standi tsaddressis
stor
edint hepointerSTART.

Del
eti
ngt
heLastNodef
rom aCi
rcul
arLi
nkedLi
st
St
ep1:Begin
St
ep2:IfSTART=NULL
Writ
eUNDERFLOW
GotoStep9
[
EndofIf]
St
ep3:SetPTR=START
St
ep4:RepeatStep5to6whil
ePTR-
>NEXT!
=START
St
ep5: SetPREPTR=PTR
St
ep6: SetPTR=PTR->NEXT
[
Endofloop]
St
ep7:SetPREPTR- >NEXT=START
St
ep8:FREEPTR
St
ep9:Stop
Int heabovealgor
ithm,instep2,wet akeapointervari
abl
ePTRandi ni
ti
ali
zeitwithSTART.
Thatis,PTRnowpoi nt
st othefi
rstnodeoftheli
nkedl
ist.I
nthewhil
eloop,wet akeanotherpoi
nter
var
iable,PREPTRsucht hatPREPTRal way
spointstoonenodebeforePTR.Oncewer eachthelast
nodeandt hesecondlastnodetoSTART, sothati
tnowbecomest helastnodeoft hel
inkedli
st.
29

Appl
i
cat
ionsofLi
nkedLi
sts:
Li
nkedlist
scanbeusedt or
epr
esentpol
ynomi
alsandt
hedi
ff
erentoper
ati
onst
hatcanbe
per
for
medont hem.
Pol
ynomialRepresent
ati
on:

STACKSANDQUEUES
STACKS
St
acksar
eimpor
tantdat
ast
ruct
ureswhi
chst
orest
hei
rel
ement
sinanor
der
edmanner
.
Astackisal i
neardatastr
ucture,i
nwhichalli
nserti
onsanddel
eti
onsareperfor
medatone
end,cal
ledthetop.Thatmeans,new el ementisaddedattopofthestackandanel ementi
s
removedfrom t
hetopoft hestack.Inst
ack,thei
nsert
ionanddel
eti
onoperat
ionsareper
for
med
basedonLIFO(LastI
nFirstOut
).
Mostmi cr
oprocessor
suseast ack-
basedarchit
ect
ure.Whenamet hodiscall
ed,it
sret
urn
addressandargumentsarepushedont oastack,andwheni tr
etur
ns,t
heyarepoppedoff.St
ack
remov esfr
om thet op (
LI .A st
FO) ack i
sal i
stwherei nser
ti
on and del
eti
on oper
ati
onsare
perf
ormedonlyattheheadoftheli
st.
push Pop

D
Topoft
hest
ack
C
B
A
30

St
ack
Ar
rayRepr
esent
ati
onsofSt
acks:
I
ncomput ermemory
,stackscanberepr
esent
edasal i
neararr
ay.Ever
ystackhasav ar
iabl
e
TOPassoci
atedwit
hit
,whichisusedt
ostoretheaddr
essofthetopmostelementofthestack.I
t
i
satthi
spositi
onwher
etheelementwil
lbeaddedordel
etedfr
om.Thereisanotherv
ariabl
esMAX
whi
chwi
l
lbeusedt
ost
oret
hemaxi
mum numberofel
ement
sthatt
hest
ackcanhol
d.
I
fTOP=NULL,
theni
tindi
cat
est
hatt
hest
acki
sempt
yandi
fTOP=MAX-
1,t
hent
hest
acki
sful
l
.

A B C D E
0 1 2 3 TOP=4 5 6 7 8 9
I
ntheabov
eexampl
eshowst
hatTOP=4,soi
nser
ti
onsanddel
eti
onswi
l
lbedoneatt
his
posi
ti
on.I
nthi
sst
ack,
fiv
emor
eel
ement
scanst
il
lbest
ored.
Oper
ati
onsonSt
ack:
Astacksupport
st hr
eebasi coperat
ions:push,pop,andpeep.Thepushoperati
onaddsan
el
ementtothetopoft hestackandt hepopoper at
ionremovestheelementfr
om thetopoft
he
st
ack.Thepeepoperat
ionretur
nsthev al
ueofthetopmostelementoft
hestack.
1.PushOper
ati
on:
Thepushoperati
onisusedtoinser
tanel ementi
ntothestack.Thenewel ementi
saddedat
thetopmostposi
tionofthestack.Howev er
,befor
einsert
ingthev alue,wemustfir
stchecki
f
TOP=MAX-1,asi
twoul dmeanthatthestackisful
landnof ur
therinsert
ionscanbedoneandan
Ov
erf
lowmessagei
spr
int
ed.

1 2 3 4 5
0 1 2 3 TOP=4 5 6 7 8 9
Toinsertanel
ementwit
hval
ue6,wewi
llf
ir
stchecki
fTOP=MAX-1,
ift
hecondi
ti
onisf
alsethen
wewi
l
lincrementtheval
ueofTOPandst
orethenewelementatt
hepositi
ongi
venbyst
ack[ .
TOP]
Thus,
theupdat
edst
ackbecomesasshownbel
ow.
1 2 3 4 5 6
0 1 2 3 4 TOP=5 6 7 8 9
Al
gor
it
hm:
St
ep1:Begi
n
St
ep2:I
fTOP=MAX-
1,t
hen
31

Pri
nt“StackOv
erf
low”
GotoStep5.
[EndofIf]
St
ep3:SetTOP<-TOP+1
St
ep4:SetStack[
TOP]<-VALUE
St
ep5:End
Theabovealgor
it
hm i
susedtoi
nsertanelementi
nt hest
ack.InSt
ep2,wefir
stcheckfort
he
over
fl
owcondit
ion.I
nstep3,TOPisi
ncrementedsot hati
tpoint
stothenextf
reelocat
ionint
he
st
ack.I
nStep4,theval
uei
sstor
edinthestackatt
helocati
onpoint
edbyTOP.
2.PopOper
ati
on:
Thepopoper at
ionisusedtodelet
ethetopmostelementfr
om t
hest ack.However
,bef
ore
deleti
ngthev
alue,wemustfir
stchecki
fTOP=NULL,asi
twouldmeanthatthestacki
semptyand
theref
orenofur
therdel
eti
onscanbenodeandanUnderf
lowmessagei
sprinted.
Todel
etet
het
opmostel
ement
,wewi
l
lfi
rstchecki
fTOP=NULL.I
fthecondi
ti
oni
sfal
set
hen
wewi
l
ldecr
ementt
hev
alueofTOP.Theupdat
edst
ackbecomesasshownbel
ow.
Al
gor
it
hm:
St
ep1:Begi
n
St
ep2:I
fTOP=NULLt hen
Pr
int“St ackUnder
fl
ow”
GotoSt ep5.
[EndofIf]
St
ep3:SetVAL=St ack[TOP]
St
ep4:SetTOP=TOP- 1
St
ep5:End
Theabov
eal
gor
it
hm t
odel
eteanel
ementf
rom t
hest
ack.I
nst
ep1,wef
ir
stcheckf
ort
he
under
fl
owcondit
ion.I
nstep2,t
hev al
ueoft
hel
ocat
ioni
nthest
akedpoi
ntedbyTOPi
sst
oredi
n
VAL,I
nstep3,
TOPi sdecr
emented.

St
ackOper
ati
ons
Push(
x)
I
nser
ttheel
ementxt
othet
opoft
hest
ack
Pop(
)
Remov
eel
ementf
rom t
het
op
Top(
)
Checkt
henextel
ementt
ober
emov
ed(
donotr
emov
e)
peek(
)
32

Looksatt
heel
ementatt
het
opoft
hisst
ackwi
thoutr
emov
ingi
tfr
om t
hest
ack.
PeekorTop
Ret
urnsacopyoft
heobj
ectont
opoft
hest
acki
fthest
acki
snotempt
y.
I
sEmpt
y()
Checkwhet
hert
hest
acki
sempt
y.
Si
ze
r
etur
nst
henumberofobj
ect
son(
cur
rent
lyst
oredi
n)t
hest
ack,
ani
nteger
.
I
sFul
l
r
etur
nst
ruei
fthest
acki
sempt
y(si
zeequal
szer
o).
Eg:

LetastackSbegi
nasempt y,t
henletuspush1ontothest
ack.Thi
sisshowninStep1.Next
,
wepushtheval
ues2and3ontothestack,asshowni
nSteps2and3.IfShascapaci
tyn=3,then
Si
sfull
.Poppi
ngthev
aluesof
fthestackasshowninSt
eps4-6thensi
ze=0(emptystack)
.

Eg:

i
mpor

jav
a.ut
il
.St
ack;
publ
ic 
class 
StackExampl
e {
 
 publ
ic 
stat
ic 
voi
d mai
n(St
ri
ng 
args[
])
 {
 
  
 St
ack 
s = 
new 
Stack(
);
33

 
  
 s.
push(
"Jav
a")
;
 
  
 s.
push(
"Sour
ce"
);
 
  
 s.
push(
"and"
);

 
  
 Sy
stem.
out
.pr
int
ln(
"Next


+ s.
peek(
));
 
  
 s.
push(
"Suppor
t")
;
 
  
 Sy
stem.
out
.pr
int
ln(
s.pop(
));
 
  
 s.
push(
".
")
;
 
  
 i
nt 
count
 = 
s.sear
ch(
"Jav
a")
;
 
  
 whi
le 
(count
 !
= -
1 && 
count
 > 
1) 
{
 
  
  
 s.
pop(
);
 
  
  
 count
--
;
 
  
 }
 
  
 Sy
stem.
out
.pr
int
ln(
s.pop(
));
 
  
 Sy
stem.
out
.pr
int
ln(
s.empt
y()
);
 
 }
}

Out
put
:

Next
:and

Suppor
t

Jav
a

Tr
ue

Pus
hOpe
rat
i
on
Theprocessofputt
inganew datael
ementont
ost acki
sknownasaPushOper
ati
on.Push
oper
ati
oninvol
vesaser
iesofst
eps−

 St
ep1 
−Checksi
fthest
acki
sful
l
.

 St
ep2 
−Ift
hest
acki
sful
l
,pr
oducesaner
rorandexi
t.

 St
ep3 
−Ift
hest
acki
snotf
ull
,i
ncr
ement
s t
op 
topoi
ntnextempt
yspace.

 St
ep4 
−Addsdat
ael
ementt
othest
ackl
ocat
ion,
wher
etopi
spoi
nti
ng.

 St
ep5 
−Ret
urnssuccess.

Asi
mpl
eal
gor
it
hm f
orPushoper
ati
oncanbeder
ivedasf
oll
ows−

begi
npr
ocedur
epush:
stack,
dat
a
34

i
fst
acki
sful
l
r
etur
nnul
l
endi
f
t
op← t
op+1
st
ack[
top]← dat
a
endpr
ocedur
e

PopOpera
tion
Accessi
ngthecontentwhil
eremov ingitf
rom thestack,i
sknownasaPopOper at
ion.I
nanarray
i
mplementati
onofpop( )operati
on,thedat aelementi snotactual
l
yremoved,inst
ead 
top 
is
decr
emented to alowerposi ti
on inthest ackto pointt
ot henextval
ue.Buti nli
nked-
li
st
i
mplementati
on,pop()act
uall
yremov esdataelementanddeall
ocat
esmemoryspace.

APopoper
ati
onmayi
nvol
vet
hef
oll
owi
ngst
eps−

 St
ep1 
−Checksi
fthest
acki
sempt
y.

 St
ep2 
−Ift
hest
acki
sempt
y,pr
oducesaner
rorandexi
t.

 St
ep3 
−Ift
hest
acki
snotempt
y,accessest
hedat
ael
ementatwhi
cht
op 
i
spoi
nti
ng.

 St
ep4 
−Decr
easest
hev
alueoft
opby1.

 St
ep5 
−Ret
urnssuccess.

Asi
mpl
eal
gor
it
hm f
orPopoper
ati
oncanbeder
ivedasf
oll
ows−

begi
npr
ocedur
epop:
stack
i
fst
acki
sempt
y
r
etur
nnul
l
endi
f
dat
a← st
ack[
top]
t
op← t
op-1
r
etur
ndat
a
endpr
ocedur
e

Pol
i
shNot
ati
ons:
I
nfi
x,post
fi
x,andpr
efi
xnot
ati
onsar
ethr
eedi
ff
erentbutequi
val
entnot
ati
onsofwr
Theusualnot at
ionforwri
ti
ngarit
hmet i
cexpr essionsiscall
edinfixnotat
ion,inwhi chthe
operatori
swritt
enbet weent
heoperands.Forexampl e,intheexpr
essiona+b,t heoperati
on+i s
betweentheoper andsaandb.Ininf
ixnotati
on,t
heoper at
orshaveprecedence.Thatis,wemust
eval
uat eexpr
essionsf r
om l
eftt
or i
ght,andmul t
ipli
cationanddivisi
onhav ehigherprecedence
35

t
hanaddi
ti
onandsubt
ract
ion.I
fwewantt
oev
aluat
etheexpr
essi
oni
nadi
ff
erentor
der
,wemust
i
ncl
udepar
entheses.Forexampl
e,int
heexpr
essi
ona+b*c,wefi
rstev
aluat
e*usi
ngt
heoper
ands
bandc,
andthenweev aluat
e+usingt
heoper
andaandtheresul
tofb*c.
I
nt heear l
y1920s,t hePol i
shmat hematicianJanLukasi ewi
csdi scoveredt hati foperators
werewr it
tenbef or
et heoperands(pr
efixorPolishnot at
ion;f
orexampl e,+ab),thepar enthesescan
beomi tted.Inthel ate1950s,theAust al
i
anphi losopherandear l
ycomput ersci ent
istChar l
esL.
Hambl i
npr oposedaschemei nwhi chtheoper atorsfol
low theoper ands( postf
ixoper ators)
,
resul
ti
ngi ntheRev ersePolishnotat
ion.Thishast headv antagesthattheoper atorsappeari nt he
orderrequir
edf orcomput at
ion.

Appl
i
cat
ionsofSt
acks:
Rev
ersi
ngaLi
st:
Ali
stofnumberscanber eversedbyr
eadingeachnumberfrom anarr
ayst
art
ingf
rom t
hef
ir
st
i
ndexandpushi
ngitonast ack.Onceallt
henumber shavebeenread,
thenumber
scanbepopped
oneatati
meandthenstoredint hearr
aystar
ti
ngfrom t
hefir
sti
ndex.
I
mpl
ement
ingPar
ent
hesesChecker
:
St
ackscanbeusedt ocheckt hev al
i
dityofparent
hesesinanyal gebraicexpr
essi
on.For
example,analgebr
aicexpr
essioni
svali
difforever
yopenbracketthereisacor r
espondi
ngclosi
ng
bracket
.Forexample,t
heexpressi
on(A+B}isinv
ali
dbutanexpression{A+(B-C)}i
svali
d.
Ev
aluat
ionofExpr
essi
ons:
St
acki
susedt
oev
aluat
epr
efi
x,post
fi
xandi
nfi
xexpr
essi
ons.
Conv
ersi
onofanexpr
essi
on:
Anexpressi
oncanber epr
esent
edi npr
efi
x,post
fi
xori
nfi
xnot
ati
on.St
ackcanbeusedt
o
conv
ertoneform ofexpr
essi
ontoanother
.
Sy
ntaxPar
sing:
Manycompi
ler
suseastackf
orpar
singt
hesy
ntaxofexpr
essi
ons,
progr
am bl
ockset
c.bef
ore
t
ransl
ati
ngi
ntol
owlev
elcode.
Funct
ioncal
l
:
St
acki
susedt
okeepi
nfor
mat
ionaboutt
heact
ivef
unct
ions.
36

QUEUES
A queuei
sal
i
neardat
ast
ruct
ure,sequent
iall
i
stofi
temst
hatar
einser
tedandr
emov
ed
accor
dingt
otheFi
rst
-I
n-Fi
rst
-Out(
FIFO)pr
inci
ple.Thati
sthef
ir
sti
tem i
nser
tedi
naqueuei
sal
so
t
hef
ir
stonet
obeaccessed,t
hesecondi
tem i
nser
tedi
naqueuei
sal
sot
hesecondonet
obe
accessed,
andt
hel
astonet
obei
nser
tedi
sal
sot
hel
astonet
obeaccessed.
I
nthequeueonl
ytwooper
ati
onsar
eal
l
owedenqueueanddequeue.Enqueuemeanst
oinser
t
37

ani
tem i
ntot
hebackoft
hequeue,
dequeuemeansr
emov
ingt
hef
ronti
tem.
Ar
rayRepr
esent
ati
onofQueues:
Queuesar
eeasi
l
yber
epr
esent
edusi
ngl
i
nearar
ray
s.Ev
eryqueuewi
l
lhav
efr
ontandr
ear
v
ari
abl
est
hatwi
l
lpoi
ntt
otheposi
ti
onf
rom wher
edel
eti
onsandi
nser
ti
ons,r
espect
ivel
y,canbe
per
for
med.Thear
rayr
epr
esent
ati
onofaqueuei
sshownbel
ow:
10 12 30 14 15 60
0 1 2 3 4 5 6 7 8 9
Oper
ati
onsonQueues:
I
nser
ti
on:
I
ntheabov
eexampl
e,f
ront
=0andr
ead=5.I
fwewantt
oaddonemor
eval
uei
nthel
i
st,
thati
s
45,t
henr
earwoul
dbei
ncr
ement
edby1andt
hev
aluewoul
dbest
oredatt
heposi
ti
onpoi
ntedby
r
ear
.Thequeueaf
teraddi
ti
onwoul
dappearasshownbel
ow:
10 12 30 14 15 60 45
0 1 2 3 4 5 6 7 8 9
Her
e,f
ront
=0andr
ear
=6.Ev
eryt
imeanewel
ementhast
obeadded,wewi
l
lrepeatt
hesame
pr
ocedur
e.
Al
gor
it
hm:
St
ep1:Begi
n
St
ep2:I
fREAR=SI ZE-1,then
Pri
nt“Overfl
ow”
GotoStep5.
[EndofIf]
St
ep3:I
fFORNT=- 1andREAR=-1,t
hen
SetFRONT<-0
SetREAR<-0
Else
SetREAR=REAR+1
St
ep4:SetQUEUE[REAR]<-VALUE
St
ep5:End
Theabov
eal
gor
it
hm i
nst
ep2,
wef
ir
stcheckf
ort
heov
erf
lowcondi
ti
on.I
nst
ep3,
wechecki
f
t
hequeuei
sempt
y.I
ncaset
hequeuei
sini
ti
all
yempt
y,t
hent
hev
alueoff
rontandr
earar
esett
o
zer
o,sot
hatt
henew v
aluecanbest
oredatt
hezer
othl
ocat
ion.Ot
her
wise,i
fthequeueal
ready
hassomev
alues,
thenr
eari
sincr
ement
edsot
hati
tpoi
ntst
othenextf
reel
ocat
ioni
nthear
ray
.In
st
ep4,
thev
aluei
sst
oredi
nthequeueatt
hel
ocat
ionpoi
ntedbyr
ear
.
Del
eti
on:
38

I
fwewantt
odel
eteanel
ementf
rom t
hequeue,t
hent
hev
alueoff
rontwi
l
lbei
ncr
ement
ed.
Del
eti
onsar
edonef
rom onl
ythi
sendoft
hequeue.Thequeueaf
terdel
eti
onwi
l
lbeasshown
bel
ow.
12 30 14 15 60 45
0 1 2 3 4 5 6 7 8 9
Her
e,f
ront
=1andr
ear=6
St
ep1:Begi
n
St
ep2:I
fFRONT=- 1,t
hen
Pr
int“Underf
low”
Got oStep5.
[EndofIf]
St
ep3:SetVAL<-QUEUE[ FORNT]
St
ep4:SetFRONT<-FRONT+1
St
ep5:End

QueueOper
ati
ons
• Enqueue(
x)
i
nser
ttheel
ementxt
othet
ail
oft
hequeue
• Dequeue(
)
r
emov
ethef
ir
stel
ementf
rom t
heheadoft
hequeue
• Top(
)
checkt
henextel
ementt
ober
emov
ed(
donotr
emov
e)
• I
sEmpt
y()
whet
hert
hequeuei
sempt
y
• Si
ze(
)
Ret
urnst
henumberofobj
ect
sint
hequeue,
whi
chi
sani
nteger
.
• I
sFul
l
()
Ret
urnst
ruei
fthequeuei
sful
lot
her
wisef
alse.
39

Exampl
e.LetaqueueQst oretheelements1,2,and3,where1i satt
hefrontofthequeue.
ThisisshowninFi
gure2.4.3,St
eps1-3,below.I
fQhasf i
nit
ecapaci
ty,
thenwecandetectthatQis
ful
l
.Dequeueingoft
hev alues1,2,and3i sshowninFi
gure2.4.
3,St
eps4-6,
whichyiel
dsanempt y
queue.

Ci
rcul
arQueue
Circul
arQueueisali
neardatastr
uctur
einwhi cht
heoperati
onsar
eperf
ormedbasedonFI
FO
(Fi
rstInFi
rstOut
)pri
nci
pleandthelastposi
ti
onisconnect
edbacktot
he
fi
rstposi
ti
ontomakeacir
cle.
InanormalQueue,wecani nser
tel
ementsunti
lqueuebecomesful
l
.
Butoncequeuebecomesf ull
,wecannoti
nsertt
henextelementeveni
f
ther
eisaspacei
nfrontofqueue.
I
nanor malqueue,thedelet
edporti
oniswasted.Toovercomethe
dr
awbackofqueuet heci
rcul
arqueuewasimpl
ementedi
nthi
stechni
quethedel
etedpor
ti
onal
so
beut
il
izedorr
euse.
40

I
mpl ement ati
onofCi rcularQueues:
The ci rcularqueue wi llbe ful
l
yonl ywhen f r
ont=0 and rear
=max-1.A cir
cularqueue i
s
i
mpl ement edi nthesamemannerasal inearqueuei si
mplement ed.Theonlydi
ff
erencewil
lbein
thecodet hatper for
msi nserti
onanddel eti
onoper ati
ons.
I
nser t
ion:
Forinsert
ion, wenowhav et
ocheckf orthef ol
lowing3condi t
ions:
 I ff
ront =0andr ear=max-1,t
hent hecircularqueueisfull
.

10 12 30 14 15 60 45 50 65 95
FRONT=0 1 2 3 4 5 6 7 8 REAR=9

 I
fREAR!
=MX-
1,t
henREARwi
l
lbei
ncr
ement
edandt
hev
aluewi
l
lbei
nser
ted.

10 12 30 14 15 60 45 50 65
FRONT=0 1 2 3 4 5 6 7 REAR=8 9

 I
fFRONT! =0andREAR=MAX-
1,i
tmeanst
hatt
hequeuei
snotf
ull
.So,setREAR=0and
i
nser
tthenewel
ementt
her
e.

30 14 15 60 45 50 65 90
0 1 FRONT=2 3 4 5 6 7 8 9
Al
gor
it
hm:
St
ep1:Begin
St
ep2:IfFRONT=0andREAR=MAX- 1,t
hen
Pr
int“Over
fl
ow”
GotoStep5.
[
EndofIf]
St
ep3:IfFORNT=-
1andREAR=-1,t
hen
41

SetFRONT<-0
SetREAR<-0
ElseI
fFRONT! =0andREAR=MAX-1,
then
SetREAR=0
Else
SetREAR=REAR+1
[Endofif]
[Endofif]
St
ep4:SetQUEUE[REAR]<-VALUE
St
ep5:End

Intheabov ealgori
thm,instep2,wecheckf ort
heoverf
lowcondit
ion.I
nst
ep3,wemaket wo
checks.Fi
rsttoseei fthequeueisempt y
,andsecondtoseeift
heREARendhasalreadyreached
themaximum capaci tywhil
etherearecertai
nfreel
ocat
ionsbef
oretheFRONTend.Instep4,the
val
ueisstoredinthequeueatt helocat
ionpoint
edtheREAR.

Del
eti
on:
Todeleteanelement,
againwecheckf
or3condi
ti
ons.
 IfFRONT=- 1,thenther
earenoelement
sinthequeue.So,anunder
fl
ow condi
ti
onwi
l
lbe
pr
inted.

0 1 2 3 4 5 6 7 8 9
FRONT=REAR=1

 I
fthequeueisnotemptyandFRONT=REAR,
thenaf
terdel
eti
ngt
heel
ementatt
hef
rontt
he
queuebecomesemptyandsoFRONTandREARaresetto-1.

81
0 1 2 3 4 5 6 7 8 9
FRONT=REAR=9

 I
fthequeueisnotempt
yandFRONT=MAX-
1,t
henaf
terdel
eti
ngt
heel
ementatt
hef
ront
,
FRONTissett
o0.

10 56 24 56 58 98 81
0 1 2 3 4 REAR=5 6 7 8 FRONT=9

Al
gor
it
hm:
St
ep1:Begin
St
ep2:IfFRONT=-
1,t
hen
42

Pri
nt“Overf
low”
GotoStep5.
[EndofIf]
St
ep3:SetVAL=QUEUE[FRONT]
St
ep4:I
fFRONT=REAR
SetFRONT<-REAR<-0
ElseI
fFRONT=MAX- 1,t
hen
SetFRONT=0
Else
SetFRONT<-FRONT+1
[Endofif]
[Endofif]
St
ep5:End

I
ntheabov
eal
gor
it
hm,i
nst
ep2,wecheckf
ort
heunder
fl
owcondi
ti
on.I
nst
ep3,t
hev
alueoft
he
queueatt
hel
ocat
ionpoi
ntedbyFRONTi
sst
oredi
nVAL.I
nst
ep4,wemaket
wochecks.Fi
rstt
o
seei
fthequeuehasbecomeempt
yaf
terdel
eti
onandsecondt
oseei
fFRONThasr
eachedt
he
maxi
mum capaci
tyoft
hequeue.Thev
alueofFRONTi
sthenupdat
edbasedont
heout
comeof
t
hesechecks.

Doubl
eEndedQueue(
Dequeue)
DoubleEndedQueuei salsoaQueuedat ast r
uctureinwhi cht
heinser
ti
onanddel et
ion
oper
ationsar
eperf
ormedatboththeends(fr
ont and 
rear
).Thatmeans,
wecaninser
tatbot
hf r
ont
andrearposi
ti
onsandcandel
etefrom bot
hfrontandrearposit
ions.

Doubl
eEndedQueuecanber epr
esent
edi
nTWO
ways,
I
nputRest
ri
ctedDequeue

Out
putRest
ri
ctedDequeue

I
nputRestr
ict
edDequeue
I
nthisdequeue,
inser
ti
onscanbedoneonl
yoneoft
heends,
whi
l
edel
eti
onscanbedonef
rom
bot
hends.

Out
putRest
ri
ctedDequeue
Inthi
sdequeue,
delet
ionscanbedoneonl
yatone
oftheends,whi
l
einserti
oncanbedoneonbot
h
ends.
43

Pr
ior
it
yQueue:
Apri
orit
yqueueisadatastr
uctur
einwhicheachelementi
sassi
gnedapr
ior
it
y.Theprior
it
yof
theel
ementwi l
lbeusedt odeter
minetheorderinwhichtheel
ementswil
lbeprocessed.The
gener
alr
ulesofprocessi
ngt
heelementsofapri
ori
tyqueueare
 Anel
ementwi
thhi
gherpr
ior
it
yispr
ocessedbef
oreanel
ement
swi
thal
owerpr
ior
it
y.

 Twoelement
swi
tht
hesamepr
ior
it
yar
epr
ocessedonaf
ir
st-
come-
fi
rst
-ser
ved(
FCFS)
basi
s.

Apri
ori
tyqueuecanbet houghtofasamodifi
edqueueinwhichwhenanel
ementhast
obe
r
emovedfr
om thequeue,
theonewi t
hthehi
gh-
pri
ori
tyi
sret
ri
evedf
irst
.
Pri
ori
tyqueuesar
ewi del
yusedi
noper
ati
ngsy
stem toexecut
ethehi
ghestpri
ori
typrocessfi
rst
.
Thepri
ori
tyoft heprocessmaybesetbasedont heCPU t i
meitrequir
est o getexecuted
compl
etel
y.
Ar
rayRepr
esent
ati
onofaPr
ior
it
yQueue:
Whenarraysareusedt oimplementapr
ior
it
yqueue,thenaseparat
equeueforeachpriori
ty
numberismaint
ained.Eachofthesewil
lbei
mplementedusingcir
cul
ararr
aysorci
rcul
arqueues.
Ever
yindi
vi
dualqueuewillhav
eitsownFRONTandREARpoi nter
s.
Weuseat wo-dimensi
onalar
rayforthi
spur posewhereeachqueuewil
lbeal
locatedt
hesame
amountofspace.Thetwo-
dimensional
representati
onofapri
ori
tyqueueasgi
venbelow:
FRONT REAR 1 2 3 4 5
3 3 1 A
1 3 2 B C D
4 5 3 E F
4 1 4 I G H
………….
.Pr
ior
it
yQueueMat
ri
x………………….
FRONT[
K]andREAR[
K]cont
aint
hef
rontandr
earv
aluesofr
ow k,wher
eki
sthepr
ior
it
y
number.
I
nser
ti
on:
Toinser
tanewel ementwit
hpri
ori
tykinthepri
ori
tyqueue,
addt heelementatt
her earandof
rowk,wherekistherownumberaswellasthepr
iori
tynumberofthatelement
.Forexampl e,
ifwe
havet
oinsertanelementRwit
hpri
ori
ty3,t
henpri
ori
tyqueuewill
begi v
enasshownbel ow:
FRONT REAR 1 2 3 4 5
44

3 3 1 A
1 3 2 B C D
4 5 3 E F
4 1 4 I G H
…………Pr
ior
it
yqueuemat
ri
xaf
teri
nser
ti
onofanewel
ement
…………
Del
eti
on:
Todel
eteanel
ement,wefi
ndthefi
rstnon-emptyqueueandthenprocesst
hefr
ontel
ementof
thef
ir
stnon-
emptyqueue.I
nthepri
ori
tyqueuet hefi
rstnon-
emptyqueuei st
heonewit
hpri
ori
ty
number1andthef
rontel
ementi
sA,soAwi llbedelet
edandprocessedfi
rst
.
Li
nkedRepr
esent
ati
onofaPr
ior
it
yQueue:
Whenapr i
ori
tyqueueisi
mpl ementedusingal i
nkedl
ist
,theneverynodeoft helisthavethr
ee
parts:a)t
heinfor
mationordatapart,b)theprior
it
ynumberoft heelement,andc)t headdressof
thenextelement.I
fwear eusingasor t
edl i
nkedli
st,t
hentheelementwitht hehigherprior
it
ywill
precedetheel
ementwi t
hthelowerprior
it
y .

Appl
i
cat
ionsofQueues:
 Queuesar
ewi
del
yusedaswai
ti
ngl
i
stsf
orasi
ngl
eshar
edr
esour
cel
i
kepr
int
er,
disk,
CPU.

 Queuesareusedtotr
ansf
erdataasynchr
onousl
y(dat
anotnecessar
il
yrecei
vedatsame
r
ateassent)bet
weent
woprocesses,
e.g.
,pi
pes,f
il
eIO,
socket
s.

 Queuesar
eusedasbuf
fer
sonMP3pl
ayer
sandpor
tabl
eCDpl
ayer
s,i
Podpl
ayl
i
st.

 Queuesar
eusedi
nPl
ayl
i
stf
orj
ukeboxt
oaddsongst
otheend,pl
ayf
rom t
hef
rontoft
he
l
ist
.

 Queuesar eusedi noper


ati
ngsy st
em forhandli
ngint
err
upts.Whenpr ogr
ammingar eal
-
ti
mesy st
em thatcanbei nt
errupt
ed,forexample,byamousecl i
ck,iti
snecessar
yt o
processthei
nterr
uptsimmediatel
y,bef
oreproceedi
ngwit
ht hecur
rentj
ob.Ift
heint
err
upts
hav etobehandl edintheor derofarri
val
,thenaFI FO queueistheappropri
atedata
struct
ure.
45

EnqueueOper
ati
on
Queuesmaint
aintwodatapointer
s, 
front and 
rear
.Theref
ore,i
tsoper
ati
onsar
ecompar
ati
vel
y
di
ff
icul
ttoi
mplementt
hanthatofstacks.

Thef
oll
owi
ngst
epsshoul
dbet
akent
oenqueue(
inser
t)dat
aint
oaqueue−

 St
ep1 
−Checki
fthequeuei
sful
l
.

 St
ep2 
−Ift
hequeuei
sful
l
,pr
oduceov
erf
lower
rorandexi
t.

 St
ep3 
−Ift
hequeuei
snotf
ull
,i
ncr
ement
 r
ear
 poi
ntert
opoi
ntt
henextempt
yspace.

 St
ep4 
−Adddat
ael
ementt
othequeuel
ocat
ion,
wher
ether
eari
spoi
nti
ng.

 St
ep5 
−ret
urnsuccess.

Al
gor
it
hm f
orenqueueoper
ati
on

pr
ocedur
eenqueue(
dat
a)
i
fqueuei
sful
l
r
etur
nov
erf
low
endi
f
r
ear← r
ear+1
queue[
rear
]← dat
a
r
etur
ntr
ue
endpr
ocedur
e
endpr
ocedur
e

Deque
ueOperat
i
on
Accessi
ngdat afrom t
hequeueisaprocessoft wotasks−accessthedatawher
e f
ront
 i
s
poi
nting and r emove the dat
a aft
er access. The fol
l
owing steps ar
e taken to
perf
orm dequeue 
oper
ati
on−

 St
ep1 
−Checki
fthequeuei
sempt
y.

 St
ep2 
−Ift
hequeuei
sempt
y,pr
oduceunder
fl
ower
rorandexi
t.

 St
ep3 
−Ift
hequeuei
snotempt
y,accesst
hedat
awher
e f
ront
 i
spoi
nti
ng.

 St
ep4 
−Incr
ement
 f
ront
 poi
ntert
opoi
ntt
othenextav
ail
abl
edat
ael
ement
.

 St
ep5 
−Ret
urnsuccess.

Al
gor
it
hm f
ordequeueoper
ati
on
46

pr
ocedur
edequeue
i
fqueuei
sempt
y
r
etur
nunder
fl
ow
endi
f
dat
a=queue[
fr
ont
]
f
ront← f
ront+1
r
etur
ntr
ue
endpr
ocedur
e

UNI
T-I
II
Bi
nar
ySear
chTr
ees(
BST)

I
NTRODUCTI ONTOTREES:
Treei
sanon- l
ineardatast r
ucture,i
nwhi chwecanmakel i
nkbet
weeneachandev er
ymemor y
l
ocati
oninanon-sequentialorder.
Thenodesar econnectedwi thapar entchi
ldr
elati
onshipiscal
ledasat r
ee.Int
reesther
ei s
onl
yonefirstel
ementcal l
edasr ootnodeandr emai
ningal lt
henodeswhichareconnect
edtot he
notnodearecal
ledaschi l
dren.
Therootnodei salsocalledaspar entnodeandi tistheonewhi chdoesnothaveanyparent
Thenodewi t
hnochi l
discalledasl eafnode.

A
T1 T3
T2
B C D

E F G H I

J K

Theabovef i
gureshowsat r
eewher enodeAi sther ootnode,andnodesB,CandDar echil
drenof
therootnodeandf orm sub-t
reesofthet r
eer ootedA.
BasicTerminol
ogy :
Rootnode: Ther ootnodeAi sthet opmostnodei nt hetree.IfA==NULL,thenitmeanst hetreeis
empt y.
Sub-tr
ees: IftherootnodeAi snotNULL, t
hent hetreesT1,T2andT3arecall
edthesub-t
reesofA.
Leafnode: Anodet hathasnochildreniscalledt heleafnodeort heter
minalnode.
Path: Asequenceconsecut i
v eedgesi scal l
edapat h.Forexampl e,i
ntheabov efig.
,thepath
from t
herootnodeAt onodeIisgivenas: A,D, andH
Ancestornode:Anancest orofanodei sanypr edecessornodeont hepathfr
om roott
ot hatnode.The
rootnodedoesnothav eanyancest ors.Intheabov eexampl e,nodesA,C,andGar etheancestorsof
nodeK.
47

Bi
nar
yTr
ees:
Abinarytr
eeisadat astructur ethatisdefinedasacol lect
ionofelementscall
ednodes.Ev ery
nodecont
ainsalef
tpoint
erwhi chpoi ntstotheleftchi
ld,
ar i
ghtpoint
erwhichpointst
ot heri
ghtchil
d,
andadataelement
.Everybinar
yt reehasar ootelementpoint
edbyar ootpoi
nter.Therootel
ementis
thet
opmostnodeinthetree.I
froot =NULL,thenitmeanst hatt
het r
eeisempty.

Repr
esentati
onofBinaryTreesintheMemory:
Inthecomput er
’smemor y,
abi nar
ytr
eecanbemai
ntai
nedei
therbyusi
ngal
i
nkedr
epr
esent
ati
on
orbyusingsequenti
alr
epresentat
ion.

Thei
nter
nal
str
uct
ureoft
hebi
nar
ytr
eei
sasf
oll
ows:
LeftDat
a
Right

LeftDat
a LeftDat
a
Right Right

NULL
LeftDat
a LeftDat
a
Right Right LeftDat
a
Right
NULL NULL NULL NULL
LeftDat
a LeftDat
a
Right Right

NULL NULL NULL NULL

Tr
aver
singaBi
nar
yTr
ee:
Tr
aversi
ngabinarytreeistheprocessofv
isit
ingeachnodeinthetreeexactl
yonceina
sy
stemati
cway.Unl
ikeli
neardat
astr
ucturesi
nwhichtheel
ementsar
etrav
ersedsequent
ial
l
y,t
ree
i
sanon-
li
neardat
astr
uct
ureinwhichtheel
ement
scanbet
rav
ersedi
nmanydi
ff
erentway
s.Ther
e
ar
edi
ff
erental
gor
it
hmsfort
reetr
av er
sal
s.
1.Pr
e-Or
derTr
aver
sal
:
Tot r
aver
seanon- emptybi
naryt
reeinpr
e-or
der
,thef
oll
owi
ngoper
ati
onsar
eper
for
med
r
ecursi
vel
yateachnode.Theal
gor
it
hm wor
ksby
:
a.Vi
sit
ingt
her
ootnode
b.Tr
aver
singt
hel
eftsub-
tr
ee,
andf
inal
l
y
c.Tr
aver
singt
her
ightsub-
tr
ee.

A A

Consi
dert
hegi
vent
ree,hepr
e-or
dert
rav
ersaloft
het
reei
sgi
venasA,
B,C.Rootnodef
ir
st,t
he
48

l
eftsub-
tr
ee,
andt
hent
her
ightsub-
tr
ee.Pr
e-or
dert
rav
ersal
isal
socal
l
edasdept
h-f
ir
stt
rav
ersal
.
Al
gor
it
hm:
St
ep1:Star
t
St
ep2:Repeatsteps2t o4whi l
etree!
=nul
l
St
ep3: Wr i
tetree->dat
a
St
ep4: Preorder(tree-
>left)
St
ep5: Preorder(tree-
>right)
[Endofl oop]
St
ep6:End

2.I
n-Or
derTr
aver
sal
:
To tr
aver
salanon-emptybinarytreeinin-or
der
,thef
oll
owi
ng oper
ati
onsar
eper
for
med
r
ecursi
vel
yateachnode.Theal
gori
thm worksby:
a)Tr
aver
singt
hel
eftsub-
tr
ee
b)Vi
sit
ingt
her
ootnode,
c)Tr
aver
singt
her
ightsub-
tr
ee.
Consi
dertheabovegivent
ree,thei
n-or
dertr
aver
saloft
hetr
eeisgiv
enasB,AandC.Lef
tsub-
tr
eefi
rst
,ther ootnodenext,andthentheri
ghtsub-
tr
ee.I
n-or
dertr
aver
sali
salsocal
l
edas
symmetri
ctrav
ersal.
Al
gor
it
hm:
St
ep1:Star
t
St
ep2:Repeatsteps2t o4whilet
ree!
=nul
l
St
ep3: inorder(t
ree->l
eft)
St
ep4: wr i
tetree->dat
a
St
ep4: inorder(t
ree->r
ight)
[Endofl oop]
St
ep6:End
3.Post
-Or
derTr
aver
sal
:
Totraver
salanon-emptybi
naryt
reei
npost-
order
,thef
oll
owi
ngoper
ati
onsar
eper
for
med
r
ecursi
vel
yateachnode.Theal
gor
it
hm wor
ksby
:
a)Tr
aver
singt
hel
eftsub-
tr
ee
b)Tr
aver
singt
her
ightsub-
tr
ee,
c)Vi
sit
ingt
her
ootnode.
Consi
dertheabovegiventree,t
hepost -
ordertr
aversaloft
hetr
eei
sgivenasB,
CandA.Left
sub-t
reefi
rst
,ther
ightsub-
tr
eenext,andfinal
lytherootnode.I
nthi
sal
gor
it
hm,thel
eftsub-
tr
eei
s
al
way str
aver
sedbeforetheri
ghtsub-t
reeandt her
ootnode.
Al
gor
it
hm:
49

St
ep1:Star
t
St
ep2:Repeatsteps2t o4whi letr
ee!
=nul
l
St
ep3: postorder(tree-
>left)
St
ep4: postorder(tree-
>right)
St
ep5: writ
et ree->data
[Endofl oop]
St
ep6:End

4.Lev
el-
OrderTr
aver
sal
:
50

I
nlev
el-
ordert
rav
ersal
,al
lthenodesatal
evelar
eaccessedbef
oregoi
ngt
othenextl
evel
.Thi
s
al
gor
it
hm i
sal
socal
l
edast
hebr
eadt
h-f
ir
stt
rav
ersal
algor
it
hm.
Const
ruct
ingaBi
nar
yTr
eef
rom Tr
aver
salResul
ts:
Wecanconst r
uctabinar
ytreeifwearegivenatl
easttwot r
av er
salresult
s.Thef i
rsttraversal
mustbet hein-
ordert
rav
ersalandthesecondcanbeeitherpr
e-orderorpost-ordert
raversal.Thein
-or
dertraver
salresul
twil
lbeusedt odeterminethel
eftandrightchildnodes,andt hepr e-order/
post-
ordercanbeusedtodeterminetherootnode.
Eg:
I
n-or
dert
rav
ersal
:DBEAFCG
Pr
e-or
dert
rav
ersal
:ABDECFG
Fol
l
owt
hest
epsgi
venbel
owt
oconst
ructt
het
ree:
St
ep1:Uset
hepr
e-or
dersequencet
odet
ermi
net
her
ootnodeoft
het
ree.Thef
ir
stel
ementwoul
d
bet
her
ootnode.
Step2:Elementsinthel
eftsi
deoft herootnodeinthein-
ordert
rav
ersalsequencef
rom thelef
t
sub-t
reeoftherootnode.Simil
arl
y,element
sont herightsideoftherootnodeinthein-or
der
tr
aversal
sequencefr
om t
her i
ghtsub-t
reeofther
ootnode.
Step3:Recur
siv
elysel
ecteachel
ementfr
om pre-
ordert
rav
ersalsequenceandcr
eat
eit
slef
tand
ri
ghtsub-
tr
eesfr
om thei
n-or
dertr
aver
sal
sequence.

A
A A

A A A
FC
DB FC
G
E G

A A A A A A

APPLI
CATI
ONSOFTREES:
 Treesareusedtost or
esimpl
easwellascompl
exdata.Her
esi mplemeansani
nteger
value,
char
acterv
alueandcompl
exdat
ameansast
ruct
ureorarecord.
 Treesar
eoft
enusedf
ori
mpl
ement
ingot
hert
ypesofdat
ast
ruct
uresl
i
kehasht
abl
es,
set
s,
andmaps.
 Tr
eesar
eani
mpor
tantdat
ast
ruct
ureusedf
orcompi
l
erconst
ruct
ion.
 Tr
eesar
eal
sousedi
ndat
abasedesi
gn.
 Tr
eesar
eusedi
nsy
stem di
rect
ori
es.
 Tr
eesar
eal
sowi
del
yusedf
ori
nfor
mat
ionst
orageandr
etr
iev
ali
nsy
mbol
tabl
es.
51

BI
NARYSEARCHTREES:
Abinarysearchtr
ee(BST)alsoknownasanor deredbinarytree,isavari
antofbinarytr
eesin
whicht
henodesar earr
angedinorder.I
nabi nar
ysearcht ree,allthenodesint helef
tsub-t
ree
haveav al
uelessthanthatoftherootnode.Corr
espondingly,allthenodesint heri
ghtsub-t
ree
haveavalueei
therequaltoorgr
eatert
hantherootnode.Thesamer ul
eisappl
icablet
oev er
ysub-
tr
eeint
het r
ee.

Intheabov etree,t
her ootnodeis8.Thel ef
tsub-t
reeoftherootnodeconsistsofnodes1,3,4,
6
and7.Al lt
hesenodeshav esmallervaluesthantherootnode.Therootsub-t
reeoftherootnode
consist
sofnodes10, 13and14.Recur si
vely
,eachoft hesub-
treesal
soobey sthebinar
ysearch
tr
eeconst r
aint.Forexample,int
hel eftsub-t
reeoftherootnode,3istherootandallel
ementsin
i
tsrightsub-t
ree(4,6,
7)aregreat
erthan3.
Sincet
henodesinabinar
ysearcht
reear
eordered,t
heti
meneededt
osearchanelementin
t
hetr
eeisgreat
lyr
educed.Whenev
erwesearchforanelement
,wedonotneedtotr
aversethe
ent
ir
etr
ee.
Bi
nar
ysear
cht
reesal
sospeedupt
hei
nser
ti
onanddel
eti
onoper
ati
ons.
Abi
nar
ysear
cht
reehast
hef
oll
owi
ngpr
oper
ti
es:
1.Thel
eftsub-
tr
eeofanodecont
ainsonl
ynodeswi
thkey
slesst
hant
henode’
skey
.
2.Ther
ightsub-
tr
eeofanodecont
ainsonl
ynodeswi
thkey
sgr
eat
ert
hant
henode’
skey
.
3.Thel
eftandr
ightsub-
tr
eeeachmustal
sobeabi
nar
ysear
cht
ree.
Cr
eat
eaBi
nar
ySear
chTr
ee…
Eg:45,
39,
56,
12,
40,
78
Thef
ir
stnumberi
s45andt
hisi
sther
ootnode,

Thi
sisabi
nar
ysear
cht
ree,sot
her
ear
etwochi
l
dnodesav
ail
abl
e,t
hel
eftandr
ight
.Thenext

4
52

numberi
s39,
ther
ubl
eisappl
i
ed(
lef
tisl
esst
hanpar
entnode)andsoi
thast
obet
hel
eftnode,

Thenextnumberi
s56,thisi
shighert
hant
her
ootnodesoi
tgoest
other
ightsub-
tr
eewhi
ch
happenst
obeemptyatt
hisst
age,
4

3 5

Thenextnumberi
s12.Thisislesst
hatt
herootandsoneedtobeonthel
eftsub-
tr
ee.Thi
s
number22isl
esst
han39,
soitneedst
obeonl
eftsub-
tr
eeoft
hatnode.
4

3 5

Thenextnumber34islesst
hanther
ootnodeandgr
eat
ert
hant
hef
ir
stl
eftnode,
soi
tispl
acedon
ther
ightsi
deofthel
eftsub-
tr
ee.
4

3 5

1 4

Thenextnumber70,whi
chisgreatert
hanr
ootnode,andgr
eat
ert
hanf
ir
str
ightnode,sot
his
numberi
splacedont
heri
ghtsub-
tr
ee.
4

3 5

1 4 5

OPERATI
ONSONBI
NARYSEARCHTREES:
53

1.Sear
chi
ngf
oraNodei
naBi
nar
ySear
chTr
ee:
Thesearchf unct ionisusedt ofindwhet heragi venvalueispr esenti nthet reeornot .The
searchingprocessbegi nsatt her ootnode.Thef uncti
onfir
stchecksi fthebinar ysear chtreeis
empt y.Ifi
tisempt y,thenthev aluewear esear chingforisnotpresenti nt hetree.Sot hesear ch
algori
thm ter
mi natesbydi spl
ay i
nganappr opr i
atemessage.Howev er
, iftherearenodesi nt hetree,
thent hesearchfunct ioncheckst oseei fthekeyv alueofthecurrentnodei sequalt othev al
uet o
besear ched.Ifnot ,itchecksift hevaluet obesear chedforislesst hant hev alueoft hecur r
ent
node,i nwhichcasei tshouldber ecursi
velycalledont heleftchil
dnode.I ncaset hev al
uei s
greaterthanthev alueoft hecurrentnode,itshouldber ecur
sivel
ycall
edont herightchi
ldnode.
Al
gor
it
hm:
searchEl
ement( Tree,val
)
Step1:St art
Step2:I ftr
ee->data=valortree=nul
l
Returntree
Else
I
fv al<tree-
>data
ReturnsearchEl
ement
(tr
ee-
>left
,val
)
Else
ReturnsearchEl
ement
(tr
ee-
>r i
ght,v
al)
[
Endofi f]
[Endofi f
]
Step3:St op

2.I
nser
ti
ngaNewNodei
naBi
nar
ySear
chTr
ee:
Thei
nser
tfunct
ioni
susedt
oaddanewnodewi
thagi
venv
alueatt
hecor
rectposi
ti
oni
nthe
bi
narysear
cht r
ee.Addingthenodeatthecorr
ectposi
ti
onmeanst
hatt
henew nodeshoul
dnot
vi
olat
ethepropert
iesofthebi
nar
ysear
chtree.
Al
gor
it
hm:
i
nser
t(Tr
ee,val
)
St
ep1:St art
St
ep2:I ftr
ee=null
Allocatememor yfortree
Sett r
ee->data=v al
Sett r
ee->left
=tree-
>right=nul
l
El
se
Ifval<tree->data
Insert
(tr
ee->left
,v al)
Else
Insert
(tr
ee->ri
ght,v al
)
[Endofi f
]
54

[
Endofi
f]
St
ep3:St
op

Thebel
owexampl
esi
nser
ti
ngnodeswi
thv
alue12and55i
nthegi
venbi
nar
ysear
cht
ree.
Eg-
1:
(
Step1) (
Step2) (
Step3)

4 4
4

3 5 3 5
3 5

5 7 1 5 7
5 7

Eg-
2:
(
Step1) (
Step2) (
Step3) (
Step4)

4 4 4 4

3 5 3 5 3 5 3 5

5 7 5 7 5 7 5 7

3.Del
eti
ngaNodef
rom aBi
nar
ySear
chTr
ee:
55

Thedel
etef
unct
iondel
etesanodef
rom t
hebi
nar
ysear
cht
ree.
Case1:
Del
eti
ngaNodet
hathasnochi
l
dren
(
Step1) (
Step2) (
Step3) (
Step4)

4 4 4 4

3 5 3 5 3 5 3 5

5 7 5 7 5 7 5

5 5 5 5

I
ntheabov
ebi
nar
ysear
cht
ree,
ifwehav
etodel
etenode78,
wecansi
mpl
yremov
ethi
snode
wi
thoutanyi
ssue.Thi
sist
hesi
mpl
estcaseofdel
eti
on.

Case2:
Del
eti
ngaNodewi
thOneChi
l
d
Tohandl
et hiscase,thenode’
schildissetasthechi
ldofthenode’sparent.Inotherwords,
repl
acet henodewi thitschil
d.Now ifthenodeistheleftchil
dofitsparent,thenode’schil
d
becomest heleftchi
ldoft henode’
spar ent
.Corr
espondi
ngly
,ifthenodeisther ightchi
l
dofi t
s
parent
,thenode’schil
dbecomet heri
ghtchil
dofthenode’
sparent.
(
Step1) (
Step2) (
Step3) (
Step4)

4 4 4 4

3 5 3 5 3 5 3 5

5 7 5 7 5 7 5 7

Repl
ace55wi
th54
5 5 5

I
ntheabov
ebi
nar
ysear
cht
ree,
seehowdel
eti
onofnode54i
shandl
ed.
Case3:
Del
eti
ngaNodewi
thTwoChi
l
dren
Tohandl
ethi
scase,repl
acethenode’
sval
uewit
hitsi
n-or
derpr
edecessor(l
argestv
aluei
nt he
l
eftsub-
tr
ee)ori
n-or
dersuccessor(
small
estv
aluei
ntheri
ghtsub-
tr
ee).Thein-
orderpr
edecessor

4 4
4
56

ort
hesuccessorcant
henbedel
etedusi
nganyoft
heabov
ecases.Thebel
owt
reei
showdel
eti
on
ofnodewi
thv
alue56i
sdel
eted.

3 5

5 7

7 5 7

(
Step1) (
Step1) (
Step1) (
Step1)
Repl
ace56wi
th55 Del
etel
eafnode55

Al
gor
it
hm:
delet
e(Tr
ee, val
)
Step1:St art
Step2:ifTr ee=Null
Print“ Nonodesf oundi nthet ree”
Got ostep
Step3:ifv al<Tree- >data
Delet e(Tree->left,val)
Elseifv al>Tr ee->dat a
Delet e(Tree->right, v
al)
ElseifTree- >l
eftandTr ee->r
ight
SetTemp=f i
ndLar gest
Node(Tree-
>lef
t)
SetTr ee->data=Temp- >dat
a
Del ete( Tree->l
eft,Temp->data)
Else
SetTemp=Tr ee
Step4:IfTr ee->l
eft=Nul landTr ee->right=Nul l
SetTr ee=Nul l
57

El
seI
fTr
ee->l
eft!
=Nul l
SetTree=Tree-
>left
Else
SetTree=Tree->ri
ght
St
ep5:Exi
t

Theabov
eal
gor
it
hm whi
chshowst
heal
gor
it
hm t
odel
eteanodef
rom abi
nar
ysear
cht
ree.
I
nst ep2,wef i
rstcheckift r
ee-
nul
l,becauseifitistr
ue,thent henodet obedeletedisnot
presentinthetree.Howev er,
ifthati
snotthecase,thenwechecki fthev al
uetobedeletedisl
ess
thanthecur rentnode’sdata.Incaset hev al
ueisless,wecalltheal gori
thm r
ecursi
velyonthe
node’sleftsub-t
ree,
otherwisethealgor
ithm i
scal
ledrecur
sivel
yont henode’sri
ghtsub-t
ree.
I
fwehav efoundthenodewhosev alueisequalt ov al,
thenwecheckwhi chcaseofdel eti
onit
i
s.Ifthenodetobedel etedhasbothleftandr i
ghtchildren,t
henwef i
ndthei n-
orderpredecessor
ofthenodebycal l
ingfi
ndLargest
Node(Tree-
>left)andreplacethecurr
entnode’svaluewiththatof
i
tsin-or
derpredecessor.Thenwecalldel et
e(Tree->l
eft,Temp->dat
a)todeletethei ni
ti
alnodeof
thein-
orderpr
edecessor.
I
fthenodet
obedel
eteddoesnothav
eanychi
l
d,t
henwesi
mpl
ysett
henodet
oNul
l
.
Det
ermi
ningt
heHei
ghtofaBi
nar
ySear
chTr
ee:
I
nordertodeterminet hehei
ghtofabi nar
ysearchtr
ee,wecal
cul
atetheheightoft
heleftsub-
t
reeandtheri
ght-sub-
tree.Whicheverhei
ghtisgreat
er,
1isaddedtoi
t.Ift
heheightoft
heleftsub-
t
reei
sgreaterthanthatoft heri
ghtsub-t
ree,t
hen1isaddedtothel
eftsub-t
ree,el
se1isaddedto
t
heri
ghtsub-t
ree

3 5

5 7

I
ntheaboveexampl
e,si
ncet heheightoftheri
ghtsub-t
reei
sgr
eat
ert
hant
hehei
ghtoft
hel
eftsub
-
tr
ee.Thehei
ghtoft
hetree=height(r
ightsub-
tr
ee)+1=2+1=3

Al
gor
it
hm:
height
(Tr
ee)
Step1:St ar
t
Step2:IfTree=Null
Ret
urn0
58

El
se
SetLeftHei
ght=hei
ght (
Tree-
>lef
t)
SetRightHei
ght=height(
Tree-
>ri
ght)
I
fLeftHeight>RightHeigh
Ret ur
nLeftHeight+1
El
se
Ret ur
nRightHeigh+1
[
Endofi f]
[
Endofif]
St
ep3:St
op

Det
ermi
ningt
heNumberofnodes:
Deter
mini
ngthenumberofnodesi nabinar
ysearchtr
eeissmal
l
ertodeter
mini
ngitsheight
.
Tocalcul
atet
hetotalnumberofnodesint
het r
ee,wecountt
henumberofnodesinthelef
tsub-
tr
eeandtheri
ghtsub-t
ree.
Numberofnodes=t
otal
Nodes(l
eftsub-
tr
ee)+t
otal
Nodes(
ri
ghtsub-
tr
ee)
+1

Ifweconstructanexpr
essi
ontr
ee,theinor
dertr
aver
salgi
vesusthei
nfi
xnotat
ion,t
hepr eor
der
t
raversalgi
vesustheprefi
xnot
ati
on,andthepostor
dertr
aver
salgi
vesusthepost
fixnotat
ion.The
f
oll
owi ngisanexample:
*
I
nfi
x:A*
(B+C)
A +
Pr
efi
x:*
A+BC
Post
fi
x:ABC+*
B C

Thr
eadedBi
nar
yTr
ees:
Athr
eadedbi
nar
ytr
eei
sthesameast
hatofabi
nar
ytr
eebutwi
thadi
ff
erencei
nst
ori
ngt
he
NULLpoi
nter
s.
6
6

1 4 10
4

3 8 1 3 5 8 11
5

1 7 9 1 1 2 7 7 12
2

Bi
nar
ytr
eewi
thoutt
hreadi
ng Li
nkedr
epr
esent
ati
onoft
hebi
nar
ytr
ee
59

I
nthel
i
nkedr
epr
esent
ati
on,anumberofnodescont
ainaNULLpoi
nter
,ei
theri
nthei
rlef
tor
ri
ghtfi
eldsorinboth.Thi
sspaceiswast
edinst
orageaNULLpoi
ntercanbeef
fi
cient
lyusedt
o
stor
esomeot herusef
ulpi
eceofi
nfor
mati
on.
Forexampl e,theNULLentr
iescanber epl
acedtostoreapoint
ertothein-
orderpr
edecessoror
thei n-ordersuccessorofthenode.Thesespeci alpoi
ntersarecall
edthreadsandbinarytrees
containingthreadsarecal
ledt
hreadedtrees. I nthelinkedrepr
esentat
ionofat hr
eadedbinary
tree,threadswillbedenot
edusingarr
ays.
At hr
eadedbinarytr
eemaycor r
espondt oone- wayt hr
eadi ngorat wo-wayt hreading.Inone-
wayt hreadi
ng,athreadwillappearei therintherightf
ieldort hel ef
tfieldoft henode.Aone- way
threadedtreeisalsocall
edasi ngle-threadedtree.Ift
het hreadappear sint helef
tf i
eld,thenthe
l
eftf i
eldwil
lbemadepoi nttothei n-orderpredecessorofthenode.Suchaone- wayt hreadedt r
ee
i
scal l
edal ef
t-
thr
eadedbinarytree.Ifthet hr
eadappearsi nther ightfi
eld,thenitwil
l pointtothein-
ordersuccessorofthenode.Suchaone- waythreadedtreeiscal ledaright-t
hreadedbi narytr
ee.
I
ntwo-wayt
hreadedtr
ee,
alsocal
l
edadoubl
e-t
hreadedt
ree,
thr
eadswi
l
lappeari
nbot
hthel
eft
andr
ightf
iel
dofthenode.
Whilethelef
tfi
eldwi
l
lpointt
othein-orderpr
edecessoroft
henode,ther
ightf
iel
dwil
lpoi
ntt
o
i
tssuccessor.Atwo-
waythr
eadedbinar
yt r
eeisalsocall
edaful
lyt
hreadedbi
naryt
ree.
One-
wayt
hreadi
ng:
Thei
n-or
dert
rav
ersal
oft
het
reei
s..
8,
4,
9,
2,
5,
1,
10,
6,
11,
3,
7,
12
Node5cont ai
nsaNULLpoi nterint hi
sri
ghtfiel
d,soitwil
lberepl
acedtopoi nttonode1,
whichisit
sin-
ordersuccessor.Similar
ly,ther
ightfi
eldofnode8wil
lpointt
o4,t herightfi
eldof
node9wi l
lpoi
ntto2,ther i
ghtfieldofnode10wi l
lpointt
onode6,t
her i
ghtfi
eldofthenode11
wil
lpointtonode3,andr ightfieldofnode12wi l
lcontai
nNULLbecausei thasnoi n-
order
successor
.
60

Two-
wayt
hreadi
ng:
Node5cont ainsaNULLpoi nt
erini
tsleftfi
eld,i
twil
lber epl
acedtopointtonode2,whichis
i
tsin-orderpredecessor
.Simil
arl
y,t
helef
tf i
eldofnode8wi llcont
ainNULLbecausei thasnoin-
orderpredecessor,t
helef
tfi
eldofnode7wi l
lpointto3,t
heleftfi
eldofnode9wi l
lpoi
nttonode4,
theleftfi
eldofnode10wi l
lpoi
nttonode1,theleftfi
eldofnode11wi l
lcontai
n6,andthelef
tfi
eld
ofnode12wi l
lpointt
onode7.

Adv
ant
agesofThr
eadedBi
nar
yTr
ee:
 I
tenabl
esl
i
neart
rav
ersal
ofel
ement
sint
het
ree.
 Li
neart
raversalel
imi
nat
est
heuseofst
ackswhi
chi
ntur
nconsumeal
otofmemor
yspace
andcomputertime.
 I
tenabl
est
ofi
ndt
hepar
entofagi
venel
ementwi
thoutexpl
i
cituseofpar
entpoi
nter
s.
 Sincenodescont
ainpoint
erst
oi n-
orderpredecessorandsuccessor,t
hethreadedt
ree
enablesf
orwar
dandbackwardt
rav
ersaloft
henodesasgi venbyi
n-orderf
ashi
on.

61

Thr
eadedBi
nar
yTr
ees
Abinar
ytr
eei srepresentedusi
ngarrayrepresent
ati
onorli
nkedl
istr
epr
esent
ati
on.Whena
bi
nar
ytreeisr
epresentedusingli
nkedl
istrepresent
ati
on,i
fanynodei
snothavi
ngachil
dweuse
NULLpoint
eri
nthatposi t
ion.
A.J.Perl
isandC.Thor
ntonhav eproposednew binar
yt r
eecalled"ThreadedBi
naryTr
ee",
whi
chmakeuseofNULLpoi ntertoimproveitstraver
salprocesses.Inthreadedbi
naryt
ree,
NULLpoint
ersarer
epl
acedbyrefer
encestoothernodesinthetree,
call
ed t
hreads.
ThreadedBinaryTreeisalsoabi narytr
eei
nwhichal
llef
tchi
ldpoi
nter
sthatar
e
NULLpointstoitsin-or
derpr edecessor
,andal
lri
ghtchi
ldpoi
nter
sthatareNULL
poi
ntstoit
sin-
ordersuccessor.
Ty
pesoft
hreadedbi
nar
ytr
ees:
Si
n¬gl
eThr
eaded:
eachnodei
sthr
eadedt
owar
ds 
eit
her
 t
hei
n-or
derpr
e¬de¬ces¬sor
 or
 suc¬ces¬sor(
lef

orr
ight
)
Dou¬bl
ethr
eaded:
 
eachnodei
sthr
eadedt
owar
ds 
bot
h t
hei
n-or
derpr
e¬de¬ces¬sor
 and 
suc¬ces¬sor
(
lef

andr
ight
)

HEAP TREES
Heap tree i sa
binary tr
ee which
sati
sfi
es heap
orderproperti
es.I
ntrees,t
heheaporderproperti
escanber epresentedint
wot y
pes.Theyar e:
1.Eachnodei sgreat
erthanorequaltoi
tspar ent
.
2.Eachnodei sl
essthanorequaltoitsparent.
Ifthevalueofeachnodei sgreat
erthanorequalt othev al
ueofi t
sparent
,withthemi nimum-
valueelementattherootiscall
edmin-heaptr
ee( min-
heapproper t
y).
Iftheval
ueofeachnodei sl
essthanorequalt otheval
ueofi tsparent
,wit
hmaxi mum v alueat
rootiscall
edasmax- heaptree(max-
heapproperty).
62

…..Minheap…. .…..Maxheap…. .
Abi naryheapi sausef uldat astructureinwhi chelementscanbeaddedr andomlybutonlythe
elementwi ththehighestv al
uei sr emov edincaseofmaxheapandl owestv alueincaseofmi n
heap.Abi naryt r
eeisanef fi
cientdat ast r
ucture,butabinaryheapi smor espaceef f
ici
entand
simpler.
Insert
ingaNewEl ementi naBi naryHeap:
ConsideramaxheapHwi thnel ement s.Insert
inganew v alueintotheheapi sdonei nthe
foll
owingt wost eps:
1. Addt henewv alueatt hebot tom ofHi nsuchawayt hatHi sst
illacompletebinarytr
eebut
notnecessar il
yaheap.
2. L etthenewv aluer i
set oi t
sappr opriat
epl aceinHsot hatHnowbecomesaheapaswel l.
Compar ethenewv aluewi t
hi t
spar enttochecki ttheyareinthecor r
ectorder.I
ftheyare,t
hen
thepr ocedurehalts,elset henewv alueandi t
spar ent
’sval
uear eswapped
.Eg:

54 54

45 36 45 36

27 21 18 21 27 21 18 21

11 11 99

Bi
naryHeap Bi
naryheapaft
eri
nsert
ionof99
Thef i
rstst
epsay
sthati
nserttheel
ementintheheapsothatt
heheapi
scompl
etebi
nar
ytr
ee.
Soinser
tthenewval
ueastheri
ghtchil
dofnode27intheheap.

I
nt hesecondst
ep,compare99withitsparentnodevalue.I
fitislesst
hanitsparent
’sval
ue,
thenthenewnodeisinitsappr
opr
iat
eplaceandHi saheap.Ifthenewv al
ueisgreat
erthanthat
ofit
sparent’
snode,
thenswapthetwovalues.Repeatthewholeprocessunt
ilHbecomesaheap.
63

Eg:
Const
ructamaxheapHf
rom t
hegi
vensetofel
ement
s:45,
36,
54,
27,
63,
72,
61,
18.

(
Step1) (
Step2) (
Step3) (
Step4) (
Step5) (
Step6)

45 45 45 54 54 54

36 36 54 36 45 36 45 36 45

27 27 63

(
Step7) (
Step8) (
Step9) (
Step10)

54 63 63 63

63 45 54 45 54 45 54 72

27 36 27 36 27 36 72 27 36 45

(
Step7) (
Step8) (
Step9)

72 72 72

54 63 54 63 54 63

27 36 45 27 36 45 61 27 36 45 61

18

Thememor
yrepr
esent
ati
onofHcanbegi
venasshownbel
ow:

H[
1] H[
2] H[
3] H[
4] H[
5] H[
6] H[
7] H[
8] H[
9] H[
10]

72 54 63 27 36 45 61 18

St
ep1:St
art
St
ep2:[
Addthenewv alueandseti
tspos]
Setn=n+1,pos=n
64

St
ep3:SetH[n]=val
St
ep4:[Fi
ndappr opri
atelocati
onofval]
Repeatsteps5and6whi l
epos>1
St
ep5: Setpar=pos/2
St
ep6: i
fH[pos]>H[ par]Then,
Gotost ep6
El
se
SwapH[ pos]
,H[
par]
Pos=par
[
Endofi f
]
[
Endofl oop]
St
ep7:Stop

Del
eti
nganEl
ementf
rom aBi
nar
yHeap:

Consi
deramaxheapHwi thnelement
s.Anelementisalwaysdelet
edfr
om t
her
ootoft
he
heap.So,
del
eti
nganel
ementf
rom t
heheapisdoneint
hefoll
owing3steps:

 Replacetherootnode’sval
uewi t
hthel
astnode’
sv al
uesothatHisst
il
lcompl
etetreebut
notnecessari
lyaheap
 Deletethel
astnode
 Si
nkdownt henew r ootnode’
sv al
uesothatH sati
sfi
estheheappr
opert
y.I
nt hi
sstep,
i
nterchangetherootnode’
sv al
uewit
hit
schil
dnode’sval
ue.

Her
e,thevalueofrootnode=54andt
hev
alueoft
hel
astnode=11.So,r
epl
ace54wi
th11and
del
etethel
astnode.

Eg:
65

St
ep1:Star
t
St
ep2:[Remov et hel astnodef rom t heheap]
Setlast=heap[ n],
n=n- 1
St
ep3:[I
nit
iali
zation]
Setpt r=1, left
=2,ri
ght =3
St
ep4:Setheap[ ptr]=last
St
ep5:Repeatst eps6t o8whi lel eft<=n
St
ep6: Ifheap[ pt r
]>=heap[ lef t
]andheap[ ptr]>=heap[
ri
ght
]
Got ostep9
[Endofi f]
St
ep7: Ifheap[ right]<=heap[ left]
Swapheap[ pt r],heap[
left]
Else
Swapheap[ pt r],heap[
right]
[Endofi f]
St
ep8: setleft=2* ptr,ri
ght=l eft+1
[Endofl oop]
St
ep9:Stop
66

Themai
nuseofheapt
reei
stoi
mpl
ementpr
ior
it
yqueues.Wecanr
epr
esentheapt
reesi
ntwo
way
s:

Ar
ray
srepr
esent
ati
on

Li
nkedr
epr
esent
ati
on

Ar
ray
sRepr
esent
ati
on:

Representat
ion of heap tr
ee using ar r
aysi s cal
l
ed as arr
ay repr
esent
ati
on.Int hi
s
r
epresentat
iontherootnodeiskeptatk(=1)
,leftchi
l
dendr i
ghtchi
l
dsareat2kand2k+1posi
ti
ons
r
especti
vely.

Li
nkedRepr
esent
ati
on:

Repr
esent
ati
onofheapt
reesusi
ngpoi
nter
siscal
l
edasl
i
nkedr
epr
esent
ati
on.

Wecanper
for
minser
ti
onanddel
eti
onoper
ati
onsonheapt
reesasf
oll
ows.
67

UNITIV
Graphs–Graphandi
tsRepr
esentat
ion,
GraphTr
aver
sal
s,Connect
edComponent
s,Basi
cSear
chi
ng
Techni
ques,
Mini
malSpanni
ngTrees
68

5.GRAPHS
I
NTRODUCTI
ONTOGRAPHS:
Agr
aphi
sanon-
li
neardat
ast
ruct
uret
hati
susedt
oimpl
ementt
hemat
hemat
icalconceptof
graphs.A graphi sacollecti
onofv ert
ices(al
socall
ednodes)andedgest hatconnectthese
vert
ices.Agraphi soft
enviewedasagener al
i
zati
onofthetreestr
uct
ure,
where,insteadofhav
ing
amor eparent-t
o-chil
drel
ationshi
pbetweentreenodes,anykindofcomplexrelat
ionshi
pamong
thenodescanexi st.
AgraphGisdefi
nedasanor deredset(V,E)
,wher
eV(
G)r
epr
esent
sthesetofv
ert
icesandE(
G)
r
epr
esent
stheedgesthatconnectt
heverti
ces.

A B C

D E

Theabov eexampl
e,agr aphwit
hV( G)
={A,
B,C,
D,E}andE(G)={
(A,
B),(
B,C)
,(A,
D),(
B,D)
,(D,
E),
(
C,E)}
,thatt
herear
e5vert
icesornodesand6edgesinthegraph.
Agraphcanbedi rect
edorundirect
ed.Inanundi
rect
edgraph,t
heedgesdonothav
eany
dir
ect
ionassoci
atedwiththem,i
.e.
,ifanedgei sdr
awnbetweennodesAandB,t
henthenodes
canbetrav
ersedfrom AtoBaswellasf r
om BtoA.

A B C

D E

I
nadirect
edgraph,
edgesf
orm anor
der
edpai
r.I
ftherei
sanedgefrom At
oB,
thenther
eisa
pat
hfrom Atobutnofrom Bt
oA.Theedge(A,
B)issaidtoi
nit
iat
efr
om nodeA(
alsoknownas
i
nit
ial
node)andt
ermi
nat
eatnodeB(
ter
minal
node)
REPRESENTATI
ONOFGRAPHS
Ther
ear
etwocommonway
sofst
ori
nggr
aphsi
nthecomput
ermemor
y,Theyar
e:
 Sequent
ial
repr
esent
ati
onbyusi
ngadj
acencymat
ri
x
 Li
nkedr
epr
esent
ati
onbyusi
nganadj
acencyl
i
stt
hest
orest
henei
ghbour
sofanode
usi
ngal
i
nkedl
i
st.
1.Adj
acencymat
ri
xrepr
esent
ati
on:
Anadj
acencyi
susedt
orepr
esentt
henodest
hatar
eadj
acentt
ooneanot
her
.
Si
nceanadj
acencymat
ri
xcont
ainsonl
y0sand1s,
iti
scal
l
edabi
tmat
ri
xoraBool
eanmat
ri
x.The
69
A B C D E
entri
esinthemat ri
xdependontheor deri
ngof A 0 0 0 1 0 t
he nodes wi
l
l
resul
tinadiff
erentadj
acencymat
rix.Thebelow di
agram shows
B 1 0 1 1 0
some gr aphs and t heir correspondi
ng adj
acency
mat r
ices. C 0 0 0 0 0
D 0 0 0 0 1
A B C E 0 0 1 0 0

D E
A B C D E
A 0 1 0 1 0
(
Dir
ect
edGr
aph)
B 1 0 1 1 0
C 0 1 0 0 1
D 1 1 0 0 1
E 0 0 1 1 0
A B C

D E

(
Undi
rect
edGr
aph)

2)AdjacencyList 
 
Theadj acencyli
sti
sanotherwayinwhichgraphscanber
epresent
edint
hecomput
ermemory
.
Thisstructur
econsistsofalistofal
lnodesinG.Ev er
ynodeisinturnl
i
nkedtoi
tsownli
stt
hat
contai
nst henamesofallnodesthatar
eadjacenttoi
t.

A B
A B CX

B C DX

D E C DX

D A B CX

Foradi r
ect
edgraph,t
hesum oflengt
hsofal
ltheadj
acencyl
ist
st othenumberofedges
i
nG.Howev er,foranundir
ectedgr
aph,thesum ofl
engthsofal
ltheadjacencyl
ist
sisequalto
twi
cethenumberofedgesi nGbecauseanedge(u,
v)meansanedgef r
om nodeut ovaswellas
anedgefrom nodevtou
70

GRAPHTRAVERSALALGORI
THMS:
Gr
apht
rav
ersali
sat
echni
queusedf
orsear
chi
ngv
ert
exi
nagr
aph.Thegr
apht
rav
ersali
sal
so
usedt
odeci
det
heor
derofv
ert
icest
obev
isi
tedi
nthesear
chpr
ocess.Agr
apht
rav
ersalf
indst
he
edgest
obeusedi
nthesear
chpr
ocesswi
thoutcr
eat
ingl
oops.Thatmeansusi
nggr
apht
rav
ersal
wev
isi
tal
lthev
ert
icesofgr
aphwi
thoutget
ti
ngi
ntol
oopi
ngpat
h.
Ther
ear
etwogr
apht
rav
ersal
techni
quesandt
heyar
easf
oll
ows.
..
1.DFS(
Dept
hFi
rstSear
ch)
2.BFS(
Breadt
hFi
rstSear
ch)
1.Br eadt h-fi
rstsear ch:
Br eadth- f
irstsear ch( BFS)i sagr aphsearchal gorit
hm t hatbegi nsatt her ootnodeand
exploresal lthenei ghbour i
ngnodes.Thenf oreachoft hosenear estnodes, t
healgor i
thm expl
ores
theirunexpl orednei ghbournodes, andsoon,untili
tfindst hegoal .
Algor i
thm:
Step1:Def i
neaqueueofsi zet otalnumberofver t
icesi nthegraph.
Step2:Sel ectanyv er
texasst arti
ngpointfortraversal.Visitthatvertexandi nsertiti
ntoqueue
(LIFO).
Step3:Vi sital ltheadj acentv erti
cesofthev ertexwhi chisatf rontoft hequeuewhi chi snot
visit
edandi nser t
edt hem intoqueue.
Step4:Whent hereisnonewv ert
extobev isi
tfrom t hev ert
exatf rontoft hequeuet hendelete
thatv ertexf rom t hequeue.
Step5:Repeatst ep3, 4untilqueuebecomesempt y.
Step6:Whenqueuebecomesempt yi
tproducest hef inalresultasaspanni ngtreebyr emoving
unusededges.

Eg:Consi
dert
hef
oll
owi
ngexampl
egr
apht
oper
for
m BFSt
rav
ersal
.
A B C

D E F
St
ep1:Sel
ectv
ert
exAasast
art
ingpoi
nt.I
nser
tAi
ntot
hequeue.

A B C

G
71

Step2:Visi
talladj
acentvert
exofAwhi
char
enotv
isi
ted(
B,E,
D).I
nser
tnewl
yvi
sit
edv
ert
icesi
nto
queueanddeleteAfrom queue.
A B C

D E F

Step3:Vi
sital
ladj
acent(
D)whi
char
enotv
isi
ted(
ther
eisnov
ert
ext
ovi
sit
).Sodel
etet
heDf
rom
queue.
A B C

D E F

St
ep4:Visital
ladj
acent(
E)whichar
enotv
isi
ted(
C,F)
.Inser
tednewl
yvi
sit
edv
ert
icesanddel
ete
Efr
om queue B
A C

D E F

St
ep5
A:Vi
sital
lad
Bj
acent(
B)whi
char
C enotv
isi
ted(
ther
eisnov
ert
ex)
.Sodel
eteBf
rom queue.

D E F

St
ep6
A:Vi
sital
lad
Bj
acent(
C)whC
i
char
enotv
isi
ted(
G).I
nser
tGi
ntoqueue.

D E F

St
ep7
A:Vi
sital
lad
Bj
acent(
F)whi
char
C enotv
isi
ted(
ther
eisnov
ert
ex)
.Del
eteFf
rom queue.

D E F

A B C
72

St
ep8:Vi
sital
ltheadj
acent(
G)whi
char
enotv
isi
ted(
ther
eisnov
ert
ex)
.Del
eteGf
rom t
hequeue.

Queuebecomeempt
y,sost
opBFSpr
ocess.Fi
nalr
esul
tofBFSi
sspanni
ngt
reebyr
emov
ing
unusededges.

2.Dept
h-f
ir
stsear
ch:
DFSt
rav
ersalofagr
aphpr
oducesa 
spanni
ngt
ree 
asf
inalr
esul
t.
 Spanni
ngTr
ee 
i
sagr
aph
wi
thoutl
oops.Weuse 
Stackdat
ast
ruct
ure 
wit
hmaxi
mum si
zeoft
otalnumberofv
ert
icesi
nthe
gr
apht
oimpl
ementDFSt
rav
ersal
.
Weuset
hef
oll
owi
ngst
epst
oimpl
ementDFSt
rav
ersal
..
.
 St
ep1-
 Def
ineaSt
ackofsi
zet
otal
numberofv
ert
icesi
nthegr
aph.
 St
ep2-
 Sel
ectanyv
ert
exas 
star
ti
ngpoi
nt 
fort
rav
ersal
.Vi
sitt
hatv
ert
exandpushi
tont
othe
St
ack.
 St
ep3-
 Vi
sitanyoneoft
henon-
visi
ted 
adj
acent
 ver
ti
cesofav
ert
exwhi
chi
satt
het
opofst
ack
andpushi
tont
othest
ack.
 St
ep4-
 Repeatst
ep3unt
ilt
her
eisnonewv
ert
ext
obev
isi
tedf
rom t
hev
ert
exwhi
chi
satt
he
t
opoft
hest
ack.
 St
ep5-
 Whent
her
eisnonew v
ert
ext
ovi
sitt
henuse 
backt
racki
ng 
andpoponev
ert
exf
rom
t
hest
ack.
 St
ep6-
 Repeatst
eps3,
4and5unt
ilst
ackbecomesEmpt
y.
 St
ep7-
 Whenst
ackbecomesEmpt
y,t
henpr
oducef
inalspanni
ngt
reebyr
emov
ingunused
edgesf
rom t
hegr
aph

Consi
dert
hef
oll
owi
ngexampl
egr
apht
oper
for
m DFSt
rav
ersal
.

A B C

D E F

St
ep1:Sel
ectt
hev
ert
exAasst
art
ingpoi
nt(
visi
tA)
.PushAont
otheSt
ack.
73
A B C

D E F
St
ep2:Vi
sitanyadj
acentv
ert
exofAwhi
chi
snotv
isi
ted(
B).Pushnewl
yvi
sit
edv
ert
exBont
othe
St
ack.

A B C

D E F

St
ep3:Vi
sitanyadj
acentv
ert
exofBwhi
chi
snotv
isi
ted(
C).PushCont
otheSt
ack.

A B C

D E F

St
ep4:Vi
sitanyadj
acentv
ert
exofCwhi
chi
snotv
isi
ted(
E).PushEont
otheSt
ack.

A B C

D E F

St
ep5:Vi
sitanyadj
acentv
ert
exofEwhi
chi
snotv
isi
ted(
D).Pushont
otheSt
ack.
A B C

D E F

St
ep6:Ther
eisnonewv
ert
ext
obev
isi
tedf
rom D.Sousebackt
rack.PopDf
rom t
heSt
ack.
A B C

D E F

St
ep7:Vi
sitanyadj
acentv
ert
exofEwhi
chi
snotv
isi
ted(
F).PushFont
otheSt
ack.

A B C

D E F
74

St
ep8:Vi
sitanyadj
acentv
ert
exofFwhi
chi
snotv
isi
ted(
G).PushGont
otheSt
ack.

St
ep9:Ther
eisnonewv
ert
ext
obev
isi
tedf
rom G.Sousebackt
rack.PopGf
rom t
heSt
ack.

St
ep10: Ther
eisnonewv
ert
ext
obev
isi
tedf
rom F.Sousebackt
rack.PopFf
rom t
heSt
ack.

A B C

D E F

St
ep11: Ther
eisnonewv
ert
ext
obev
isi
tedf
rom E.Sousebackt
rack.PopEf
rom t
heSt
ack.
A B C

D E F

St
ep12: Ther
eisnonewv
ert
ext
obev
isi
tedf
rom C.Sousebackt
rack.PopCf
rom t
heSt
ack.
A B C

D E F

A B C
St
ep13: Ther
eisnonewv
ert
ext
obev
isi
tedf
rom B.Sousebackt
rack.PopBf
rom t
heSt
ack.
A B C C

D E C
G

D E F
A B C

A B C C

D E C G
75

St
ep14: Ther
eisnonewv
ert
ext
obev
isi
tedf
rom A.Sousebackt
rack.PopAf
rom t
heSt
ack.

St
ackbecomesempt
y.Sost
opDFSt
rav
ersal
.Fi
nal
resul
tofSDFSi
saspanni
ngt
ree.

Mi
nimum spanni
ngt
ree
Aspanni
ngt
reeofaconnect
ed,undi
rect
edgr
aphGi
sasub-
graphofGwhi
chi
sat
reet
hat
connect
sal
lthev
ert
icest
oget
her
.Agr
aphG canhav
emanydi
ff
erentspanni
ngt
rees.Wecan
assi
gnwei
ght
stoeachedge,andusei
ttoassi
gnawei
ghtt
oaspanni
ngt
reebycal
cul
ati
ngt
he
sum oft
hewei
ght
soft
heedgesi
nthespanni
ngt
ree.Ami
nimum spanni
ngt
ree(
MST)i
sdef
ined
asaspanni
ngt
reewi
thl
esst
hanorequalt
othewei
ght
sassoci
atedwi
thi
tsedges,andt
het
otal
wei
ghtoft
het
reei
satami
nimum.
Gi
venaconnect
ed,undi
rect
edgr
aph,aspanni
ngt
reeoft
hatgr
aphi
sasubgr
aphwhi
chi
sa
t
reeandconnect
sal
lthev
ert
icest
oget
her
.A
si
ngl
egr
aphcanhav
emanydi
ff
erentspanni
ng
t
rees.
A spanni
ngt
reei
sasubsetofGr
aphG,
whi
ch has al
lthe v
ert
ices cov
ered wi
th
mi
nimum possi
blenumberofedges.Hence,a
spanni
ng t
ree does nothav
e cy
cles and i
t
cannotbedi
sconnect
ed.
.
Byt
hisdef
ini
ti
on,
wecandr
awaconcl
usi
on
t
hatev
eryconnect
edandundi
rect
edGr
aphG
hasatl
eastonespanni
ngt
ree.Adi
sconnect
edgr
aphdoesnothav
eanyspanni
ngt
ree,asi
t
76

cannotbespannedt
oal
li
tsv
ert
ices.

Appl
i
cat
i
onofSpa
nni
ngTr
ee
Spanni
ngt
reei
sbasi
cal
l
yusedt
ofi
ndami
nimum pat
htoconnectal
lnodesi
nagr
aph.
Commonappl
i
cat
ionofspanni
ngt
reesar
e
1.MSTsar
ewi
del
yusedf
ordesi
gni
ngnet
wor
ks.Fori
nst
ance,peopl
esepar
atedbyv
ary
ing
di
stances wi
tht
o be connect
ed t
oget
hert
hrough a t
elephone net
wor
k.A mi
nimum
spanni
ngt
reei
susedt
odet
ermi
net
hel
eastcost
lypat
hswi
thnocy
clesi
nthi
snet
wor
k,
t
her
ebypr
ovi
dingaconnect
iont
hathast
hemi
nimum costi
nvol
ved.
2.MSTsar
eusedt
ofi
ndai
rl
iner
out
es.Whi
l
ever
ti
cesi
nthegr
aphdenot
eci
ti
es,edges
r
epr
esentt
her
out
esbet
weent
heseci
ti
es.Nodoubt
,mor
ethedi
stancebet
weent
heci
ti
es,
hi
gherwi
l
lbet
heamountchar
ged.Ther
efor
e,MSTsar
eusedt
oopt
imi
zeai
rl
iner
out
esby
f
indi
ngt
hel
eastcost
lypat
hwi
thnocy
cles.
3.MSTsar
e al
so used t
ofi
nd t
he cheapestwayt
o connectt
ermi
nal
s,such asci
ti
es,
el
ect
roni
ccomponent
sorcomput
ersv
iar
oads,
air
li
nes,
rai
l
way
s,wi
resort
elephonel
i
nes.
4.MSTsar
eappl
i
edi
nrout
ingal
gor
it
hmsf
orf
indi
ngt
hemostef
fi
cientpat
h.

APPLI
CATI
ONSOFGRAPHS
Gr
aphsar
econst
ruct
edf
orv
ari
oust
ypesofappl
i
cat
ionssuchas:
 I
ncircui
tnet
workswherepoi
ntsofconnect
ionar
edr
awnasv
ert
icesandcomponentwi
res
becometheedgesoft
hegraph.

 I
ntr
ansportnet
wor
kswher
est
ati
onsar
edr
awnasv
ert
icesandr
out
esbecomet
heedgesof
t
hegraph.

 I
nmapst
hatdr
awci
ti
es/
stat
es/
regi
onsasv
ert
icesandadj
acencyr
elat
ionsasedges.

 I
nprogr
am fl
ow anal
ysi
swhereprocedur
esormodul
esar
etr
eat
edasv
ert
icesandcal
lto
t
hesepr
oceduresar
edrawnasedgesofthegr
aph.

 Oncewehaveagraphofapar
ti
cul
arconcept
,theycanbeeasi
l
yusedf
orf
indi
ngshor
test
pat
hs,
proj
ectpl
anni
ng,
etc.

 I
nflowchart
sorcontrol
-f
low graphs,t
hestatement
sandcondi
ti
onsi napr
ogr
am ar
e
r
epr
esentedasnodesandthefl
owofcont r
oli
srepr
esent
edbyt
heedges.

UNI
T-V
77

SORTI
NGANDSEARCHI
NG
Theterm sor
ti
ngmeansar r
angi
ngtheel
ement
soft
hear
rayi
nsomer
elev
antor
derwhi
chmay
beeit
herascendi
ngordescendi
ngorder
.
I
fAisanarr
ayofNelements,t
hentheelementsofAar
ear
rangedi
nsor
tedor
der(
ascendi
ng
or
der)i
nsuchawayt
hatA[0]<A[
1]<A[2]
…..<A[N-1]
.
Forexampl
e,i
fwehav
eanar
rayt
hati
sdecl
aredandi
nit
ial
i
zedas,
i
ntA[]={
21,
34,
11,
9,
1,
0,
22}
;
Thent
hesor
tedar
ray(
ascendi
ngor
der
)canbegi
venas,
A[]={
0,1,
9,
11,
21,
22,
34}
;
Therear
emanysor t
ingmet
hods.SuchasBubbl
esor
t,Qui
cksor
t,Sel
ect
ionsor
t,Mer
gesor
t,
I
nsert
ionsor
t,Heapsor
t
BUBBLESORT
Bubbl
esortisaverysimplesort
ingtechni
queusedt osortthelistofel
ementsineit
herofthe
order.Themet hodtakest woelementsatat ime.Itcompar estheset woelements.I
fthef i
rst
elementislessthanthesecondelement ,t
heyarelef
tundisturbed.Ifthefi
rstel
ementisgreater
thant hesecondelement,thentheyar eswapped.Thepr ocedurecont i
nueswiththenextt wo
elements,goesandendswhenalltheelementsaresort
ed.
Bubbl esortsor tsthegiv enelement sinascendi ngorindescendi ngor der
.Let‘ a’
beanar r
ayof
nelement s.Theel ementsei therar enumer icaldataoral phabets.I fwehav eanar ray‘a’of‘ n’
element sdenot edbya[ 0],
a[1]……a[n-1].Thena[ 0]iscomparedwi tha[1]andr earrangeifa[1]i
sl ess
thana[ 0],nexta[ 1]iscompar ed wi t
ha[ 2],
a[2]iscompar edwi t
ha[ 3]andsoona[ n-
2]wi tha[n-1].
t
h
Ther esultcausest helargestel ementt otaken- 1l ocat
ion.Againtheel ementsarecompar edwi th
2h
t
a[0]wi tha[1],
a[1]wi t
ha[ 2]soona[ n-3]witha[ n-2]andnextl argestel ementi splacedi nn-
l
ocat i
on.Thesamemet hodi sappliedint hesamewayf oral lt
heel ements.Bubblingthel arge
elementt ot herightatev eryi t
erati
on.Finall
ya[ 0]anda[1]arecompar ed.
Al
gor
it
hm:
St
ep1: Start
St
ep2: Repeatstep3f ori
=n-1to0
St
ep3: Repeatst ep4f orj
=0ton-1
St
ep4: Ifa[j]
>a[j
+1],t
hen
Swapa[ j
]anda[
j+1]
[Endofi f
]
[EndofI nnerl
oop]
[
EndofOut erloop]
St
ep5: Exit
78

Pr
ogr
am:
publi
ccl assBubbl e
{
publicstat i
cvoidmai n(Stringargs[]
)
{
inta[ ]
={9,59,
12, 65,99,10,40,29};
intlen=a. l
ength;
Sy stem. out.
println("Unsor t
ingList
");
for(inti=0;i
<len;i++)
{
System. out.print(+a[i
]+"" );
}
Sy stem. out.
println("");
//sor t
ing

f
or(i
nti=len;
i>0;i
--
)
{
for(i
ntj=0;
j<i
-1;j
++)
{
if
(a[j
]>a[j
+1])
{
inttemp=a[j]
;
a[j
]=a[j
+1];
a[j
+1]=temp;
}
}

}
System.out.
printl
n("
Sorti
ngList
");
for
(inti
=0;i
<len;i
++)
{
System.out.
print(
+a[i
]+"")
;
}
}
}
SELECTI
ONSORT
Sel
ect
ionsortisspecif
ical
lyanin-
placecomparisonsort
.Inthissort
ingmethod,thefi
rst
elementoftheli
stisselect
ed.Iti
scompar edrepeat
edlywi
llal
ltheelements.I
fanyelementis
foundtobelessthant
hesel ect
edel
ement ,t
hesetwoareswapped.Thi
sprocedurei
srepeat
edtil
l
79

t
heent
ir
ear
rayi
ssor
ted.
Al
gor
it
hm
Consi
deranar
rayawi
thnel
ement
s.Thesel
ect
ionsor
ttakesn-
1passest
osor
ttheent
ir
e
arrayandworksasfol
l
ows.Firstfi
ndthesmall
estvaluei
nthear
rayandplacei
tint
hef i
rstposi
ti
on.
Thenf i
ndthesecondsmallestval
ueinthearrayandplaceiti
nthesecondposit
ion.Repeatthi
s
procedureunt
ilt
heent
irear
rayissort
ed.Ther
efore,
I
nPass1,findt
heposi
ti
onposoft
hesmal
l
estv
aluei
nthear
rayandt
henswapa[
pos]anda[
0].
Thusa[
0]i
ssort
ed.
InPass2,
findtheposit
ionposofthesmal
l
estv
aluei
nsub-
arr
ayofn-
1el
ement
s.Swapa[
pos]wi
th
a[1]
.Nowa[0]anda[1]i
ssorted.
InPass3,
findtheposit
ionposofthesmal
l
estv
aluei
nsub-
arr
ayofn-
2el
ement
s.Swapa[
pos]wi
th
a[2]
.Nowa[0]
,a[1]anda[2]i
ssor
ted.
I
npassN-
1,f
indt
heposi
ti
onposoft
hesmal
l
eroft
heel
ementa[
n-2]anda[
n-1]
.Swapa[
pos]and
a[
n-2]sot
hata[
0],
a[1]
,
….,
a[n-
1]i
ssor
ted.
Eg:
Sor
tthear
raygi
venbel
owusi
ngsel
ect
ionsor
t.

39 9 81 45 90 27 72 18

Pass a[
0] a[
1] a[
2] a[
3] a[
4] a[
5] a[
6] a[
7]
1 9 39 81 45 90 27 72 18
2 9 18 81 45 90 27 72 39
3 9 18 27 45 90 81 72 39
4 9 18 27 39 90 81 72 45
5 9 18 27 39 45 81 72 90
6 9 18 27 39 45 72 81 90

Al
gor
it
hm:
St
ep1: Start
St
ep2: Repeatstep3f ori=0tol en-1
St
ep3: [
Init
iali
ze]setsmal l=i
St
ep4: Repeatstep3f orj=i+1tol en-
1
St
ep5: Ifsmall>a[i]
>,then
Setsmal l=a[j]
Setpos[ i
]
[Endofi f]
[
Endofl oop]
St
ep6: Exit
80

publ
icclassSel ect i
onSor t
{
publicstat i
cv oidmai n(Str
ingargs[])
{
inta[ ]
={ 9,45,85,6,12,90,70,
40,99};
intlen=a. l
engt h;
Syst em. out .
pr i
ntln("Unsorti
ngList")
;
for(
inti =0; i
<len;i++)
{
Syst em. out.print(
+a[i]
+"" )
;
}
Syst em. out .
pr i
ntln("");
//sorti
ng
for(i
nti=0; i
<l en;i
++)
{
i
ntsmal l=i
;
for(intj=i+1;j<len;
j++)
{
if(
a[smal l
]>a[
j])
smal l
=j;
}
i
ntt emp=a[ i];
a[i
]=a[ smal l]
;
a[smal l
]=temp;
}
Syst em. out .
pr i
ntln("Sorti
ngList"
);
for(
inti =0; i
<len;i++)
{
Syst em. out.print(
+a[i]
+"" )
;
}
}
}

I
NSERTI
ONSORT
I
nser
ti
onsor
tisaverysi
mplesort
ingal
gori
thm,i
nwhi
cht
hesor
tedar
ray(
orl
i
st)i
sbui
l
tone
el
ementatat
ime.I
nser
ti
onsortwor
ksasfol
lows:
Thear
rayofvaluest
obesort
edi sdi
vi
dedi
ntot
woset
s.Onet
hatst
oressor
tedv
aluesandt
he
ot
hercont
ainsunsort
edval
ues. 
  
  
  
Thesor
ti
ngalgori
thm wi
llpr
ocessedunt
ilt
her
eareel
ementsint
heunsor
tedset.Ther
earen
el
ementsinthearr
ay.Ini
ti
all
ytheelementwit
hindex0(assumi
nglb,l
owerbound=0)isint
he
81

sor
tedset
,restal
ltheel
ement
sar
etheunsor
tedl
i
st.
Duri
ngeachit
erat
ionoft
healgorit
hm,thef
ir
stel
ementi
ntheunsor
tedseti
spl
acedupand
i
nsert
edint
othesort
edposi
ti
oninthesort
edset
.
39 9 45 63 18 81 108 54 72 36

9 39 45 63 18 81 108 54 72 36

9 39 45 63 18 81 108 54 72 36

9 39 45 63 18 81 108 54 72 36

9 18 39 45 63 81 108 54 72 36

9 18 39 45 63 81 108 54 72 36

9 18 39 45 63 81 108 54 72 36

9 18 39 45 54 63 81 108 72 36

9 18 39 45 54 63 72 81 108 36

9 18 36 39 45 54 63 72 81 108
I
nPass1,
a[0]i
stheonl
yel
ementi
nthesor
tedset
.
I
nPass2,
a[1]wi
l
lbepl
acedei
therbef
oreoraf
tera[
0],
sot
hatt
hear
rayai
ssor
ted.
InPass3,a[
2]wil
lbepl
acedei
therbef
orea[
0],
in-
bet
weena[
0]anda[
1]oraf
tera[
1],
sot
hatt
he
arr
ayissort
ed.
I
nPassn,
a[n-
1]wi
l
lbepl
acedi
nit
spr
operpl
acesot
hatt
hear
rayai
ssor
ted.
Toinser
ttheel
ementa[
n]inthesor
tedl
ista[
0],
a[1]
,
….,
a[n-
1],
weneedtocomparea[n]wi
th
a[
n-1]
,thenwit
ha[n-
2],
thenwi
tha[n-
3]unti
lwemeetanelementa[j
]sucht
hata[
j]
<=a[
n].

I
nser
ti
onsor
t(a,
len)wher
eai
sanar
rayofl
enel
ement
s.
St
ep1: Star
t
St
ep2: Repeatstep3t o6fori=0t
on-1
St
ep3: Settemp=a[i]
St
ep4: Setj=i
-1
St
ep5: Repeatstepswhil
ea[j
]>t
empandj
>0
Seta[j
+1]=a[
j]
Setj=j
-1
[
Endofi nnerl
oop]
St
ep6: a[
j+1]=t
emp
82

[
Endofout
erl
oop]
St
ep7: Exi
t

Pr
ogr
am:
publ
iccl
assI
nser
ti
onSor
t{
publ
icst
ati
cvoi
dmai
n(St
ri
ngar
g[]
) {
i
nta[
]={
39,
9,
45,
63,
18,
81,
108,
54,
72,
36}
;
i
ntl
en=a.
lengt
h;
Sy
stem.
out
.pr
int
ln(
"Val
uesBef
oret
hesor
t:
\n"
);
f
or(
inti
=0;
i
<len;
i
++)
Sy
stem.
out
.pr
int
(+a[
i]
+""
);
Sy
stem.
out
.pr
int
ln(
);
i
nser
ti
on_
srt
(a,
len)
;
Sy
stem.
out
.pr
int
("Val
uesaf
tert
hesor
t:
\n"
);
f
or(
inti
=0;
i
<len;
i
++)
Sy
stem.
out
.pr
int
(+a[
i]
+""
);
}
publ
icst
ati
cvoi
dinser
ti
on_
srt
(i
nta[
],i
ntn)
{
f
or(
inti=1;
i<n;
i++)
{
i
ntt
emp=a[
i]
;
i
ntj
=i-
1;
whi
le(
(a[
j]
>temp)&&(
j>0)
)
{
a[
j+1]=a[
j]
;
j
--
;
}
a[
j+1]=t
emp;
}
}
}
QUI
CKSORT
Qui
cksortisafastsorti
ngalgor
it
hm, whichisusednotonlyf
oreducati
onal
purposes,but
wi
delyappl
iedinpract
ice.Ontheaverage,
ithasO(nlogn)complexi
ty,maki
ngquicksortsui
tabl
e
f
orsort
ingbigdatavol
umes.Thei deaofthealgori
thm i
squit
esimpleandonceyoureali
zeit,
you
83

canwr
it
equi
cksor
tasf
astasbubbl
esor
t.

Likemergesor
t,t
hisal
gori
thm worksbyusi
ngadi
vi
de-
and-
conquerst
rat
egyt
odi
vi
deasi
ngl
e
usor
tedarr
ayintot
wosmal l
ersub-
arrays.

1. Sel
ectanel
ementpi
votf
rom t
hear
rayel
ement
s.

2. Rearrangetheelement sinthearr
ayinsuchawayt hatal
lelementsthatar
elessthanthepi
vot
appearbeforethepivotandallelementsgreat
erthant
hepivotelementcomeaf t
eri
t.Aft
ersucha
part
it
ioni
ng,thepivotisplacedinit
sfinalposi
ti
on.Thi
siscal
ledtheparti
ti
onoperat
ion.

3. Recur
siv
elysor
tthet
wosub-
arr
ayst
husobt
ained.

Al
gor
it
hm
Thedi
vi
de-
and-
conquerst
rat
egyi
susedi
nqui
cksor
t.Bel
owt
her
ecur
sionst
epi
sdescr
ibed:
1.Chooseapiv
otvalue.Wetaketheval
ueofthemiddl
eel
ementaspivotvalue,
butitcanbe
anyval
ue,
whichisinrangeofsort
edval
ues,ev
enifi
tdoesn'
tpr
esentinthearray
.
2.Parti
ti
on.Rearr
angeel ementsi
nsuchaway , t
hatal
lel
ementswhi
char
elesserthanthe
pi
votgot otheleftpar
tofthearrayandallelementsgreat
ert
hant
hepi
vot,gototheright
partofthearr
ay.Valuesequaltothepivotcanstayinanypar
toft
hear
ray.Noti
ce,that
arr
aymaybedi vi
dedinnon-equalpart
s.
3.Sor
tbot
hpar
ts.Appl
yqui
cksor
tal
gor
it
hm r
ecur
siv
elyt
othel
eftandt
her
ightpar
ts.

PARTI
TION(
a,beg, end, loc)
St
ep1:Setleft
=beg, ri
ght=end, loc=beg, fl
ag=0
St
ep2:Repeatst eps3t o6whi lef l
ag=0
St
ep3: Repeatwhi l
ea[ loc]<=a[ ri
ght]andloc!=ri
ght
Setright=right-1
[
Endofl oop]
St
ep4: I
floc=r ightthen,
Setflag=1
ElseIfa[loc]>a[right]
Swapa[ loc]witha[r
ight]
Setloc=r i
ght
[
Endofi f]
St
ep5: i
fflag=0
Repeatwhi l
ea[ loc]
>=a[l
eft]andl
oc!=l
eft
Setlef t
=left+1
[
Endofl oop]
St
ep6: I
fl oc=left
Setf l
ag=1
84

El
seIfa[
loc]<a[
ri
ght]
Swapa[l
oc]wit
ha[
lef
t]
Setl
oc=lef
t
[
Endofif]
[
Endofif
]
[Endofl
oop]
St
ep7:Exi
t

QUICK_
SORT( ARR,BEG,END)
St
ep1:I f(
beg<end)
Call
PARTITION(
arr,
beg,end,l
oc)
Call
QUICK_SORT(ar
r,beg,
loc-
1)
Call
QUICK_SORT(ar
r,l
oc+1,end)
[
Endofif]
St
ep2:Exit

Par
ti
ti
onal
gor
it
hm i
ndet
ail

Therear etwoi ndicesi andjandatt hev er


ybeginningoftheparti
ti
onalgori
thm ipoi
ntst ot
hef i
rst
elementi nthear rayandj point
stot helastone.Thenalgori
thm mov esif
orward,unti
lanelement
withvaluegr eaterorequal tothepivotisfound.Indexjismov edbackward,
untilanelementwith
valuelesserorequal tothepivotisfound.Ifi≤jthentheyareswappedandi st
epstot henext
positi
on( i+1),j stepstothepr ev
iousone( j-1).Algor
it
hm stops,whenibecomesgr eaterthanj.

Af
terpar
ti
ti
on,al
lval
uesbeforei
-t
hel
ementar
elessorequal
thant
hepi
votandal
lval
uesaf
terj
-t
h
el
ementaregr
eaterorequalt
othepi
vot
.

Exampl
e.Sor
t{1,
12,
5,26,
7,14,
3,7,
2}usi
ngqui
cksor
t.
85
86

Pr
ogr
am f
rom Qui
ckSor
t
publ
iccl
assQui
ckSor
t

publ
icst
ati
cvoi
dmai
n(St
ri
nga[
])

i
nti
;

i
ntar
r[
]={
12,
9,
4,
99,
120,
1,
3,
10,
13}
;

Sy
stem.
out
.pr
int
ln(
" Qui
ckSor
t\n\
n")
;

Sy
stem.
out
.pr
int
ln(
"Val
uesBef
oret
hesor
t:
\n"
);

f
or(
i=0;
i<ar
r.
lengt
h;i
++)

Sy
stem.
out
.pr
int
(ar
r[
i]
+""
);

Sy
stem.
out
.pr
int
ln(
);

qui
ck_
srt
(ar
r,
0,
arr
.l
engt
h-1)
;

Sy
stem.
out
.pr
int
("Val
uesaf
tert
hesor
t:
\n"
);

f
or(
i=0;
i<ar
r.
lengt
h;i
++)

Sy
stem.
out
.pr
int
(ar
r[
i]
+""
);

publ
icst
ati
cvoi
dqui
ck_
srt
(i
ntar
r[
],i
ntf
ir
st,
intl
ast
)

i
f(
fi
rst
<last
)

i
ntpi
vot
=fi
rst
;

i
nti
=fi
rst
;

i
ntj
=last
;

whi
le(
i<j
)

whi
le(
arr
[i
]<pi
vot&&i
<last
)

i
++;

whi
le(
arr
[j
]>pi
vot
)

j
--
;

i
f(i<=j
)
87

/
**swap*
*/

i
ntt
emp=ar
r[
i]
;

ar
r[
i]=ar
r[
j]
;

ar
r[
j]=t
emp;

i
ntt
emp=ar
r[
piv
ot]
;

ar
r[
piv
ot]
=ar
r[
j]
;

ar
r[
j]
=ar
r[
i]
;

qui
ck_
srt
(ar
r,f
ir
st,
j-
1);

qui
ck_
srt
(ar
r,j
+1,
last
);

Mer
geSor
t:
Mer
gesortisasor
ti
ngal
gor
it
hm t
hatusest
hedi
vi
de,conquerandcombi
neal
gor
it
hmi
c
par
adi
gm.Where,

Dividemeansparti
ti
oni
ngthen-el
ementarr
aytobesor
tedi
ntot
wosub-arr
aysofn/2el
ements
i
neachsub- arr
ay.(
Ifai sanarraycont
aini
ngzerooroneelement
,thenitisalr
eadysort
ed.
Howev er,i
ftherear
emor eel
ement sint
hearray
,div
ideaint
otwosub-ar
rays,a1anda2,each
cont
ainingabouthal
foftheel
emtnsofa).

Conquermeanssor
ti
ngt
het
wosub-
arr
aysr
ecur
siv
elyusi
ngmer
gesor
t.

Combi
nemeansmer
gingt
het
wosor
tedsub-
arr
aysofsi
zen/
2eacht
opr
oducet
hesor
ted
ar
rayofnel
ement
.

Thebasi
cst
epsofamer
gesor
tal
gor
it
hm ar
easf
oll
ows:

 I
fthear
rayi
sofl
engt
h0or1,
theni
tisal
readysor
ted.
 Ot
her
wise,
div
idet
heunsor
tedar
rayi
ntot
wosub-
arr
aysofabouthal
fthesi
ze.
 Usemer
gesor
tal
gor
it
hm r
ecur
siv
elyt
osor
teachsub-
arr
ay.
 Mer
get
het
wosub-
arr
ayst
ofor
m asi
ngl
esor
tedl
i
st.
88

Eg:
39 9 81 45 90 27 72 18

39 9 81 45 90 27 72 18

39 9 81 45 90 27 72 18

39 9 81 45 90 27 72 18
(
Div
ideandConquert
hear
ray
)
39 9 81 45 90 27 72 18

9 39 45 81 27 90 18 72

9 39 45 81 27 18 72 90

9 18 27 39 45 72 81 90
(
Combi
net
heel
ement
stof
orm asor
tedar
ray
)

Merge(
arr
,lef
t,mid, ri
ght)
St
ep1: Star
t
St
ep2: Seti=left,j
=mid+1, index=0
St
ep3: Repeatwhi l
e(i<=mi d)and( j
<right
)
Ifa[i]
<a[j]
Settemp[ index]=a[
i]
Seti=i+1
Else
Settemp[ index]=a[
j]
Setj=j+1
[Endofi f]
Seti ndex=index+1
[
Endofl oop]
St
ep4: [Copyt heremai ningel ementsofr ightsub-
arr
ay,
ifany
]
I
fi>mi d
Repeatwhi lej<=end
Settemp[ index]=a[
j]
89

Setindex=index+1
Setj=j
+1
[Endofloop]
[
Copytheremainingelement soflef
tsub-
arr
ay,i
fany
]
El
se
Repeatwhi l
ei<mid
Settemp[index]=a[
i]
Setindex=index+1
Seti=i
+1
[Endofloop]
[
Endofi f]
St
ep5: [
Copythecontentsoftempbackt oarr
]Setk=0
St
ep6: Repeatwhilek<index
Setarr[
k]=t
emp[ k]
Setk=k+1
[
Endofl oop]
St
ep7: Exit

Merge_
Sor
t(Arr
,Left,Right)
St
ep1: Setmi d=(lef
t+right)
/2
St
ep2: I
fleft<ri
ght
Callmer ge_sort
(arr
,lef
t,mid)
Callmer ge_sort
(arr
,mid+1,ri
ght
)
Mer ge(arr
,lef
t,mid,ri
ght)
[Endofi f]
St
ep3: Exit

cl
assMergepro
{
publ
icstati
cv oidmai n(Stringar g[]
)
{
inta[]
={18,49,31,22,90,4,66};
intn=a.l
engt h;
System.out .pri
ntln(
"Unsor tedEl ement
s")
;
for(
inti=0;i<n; i
++)
{
System. out.pri
ntln(+a[i]
);
}
/*Calli
ngt hisfunctionssor tsthearr
ay*/
Mer geSort(a,0,
n-1);
for(
inti=0;i<n; i
++)
{
System. out.pri
ntln(+a[i]
);
90

}
}
publ
icstat icv oidMer geSor t(i
nta[ ],
intleft
,intri
ght
)
{
intmi d=( lef t+ri
ght)/2;
if(
left<right )
{
/*Sor tthel eftpart* /
Mer geSor t
(a,l
eft,
mi d);
/*Sor tther ightpar t* /
Mer geSor t
(a,mid+1,right);
/*Mer get hetwosor tedpar ts* /
Mer ge( a,left,
mid,right) ;
}
}
publ
icstat icv oidMer ge(inta[ ],i
ntleft,i
ntmi d,
intr
ight
)
{
inttempAr ray []
=newi nt [
right-l
eft+1];
intindex=0, i=l eft,
j=mi d+1;
whi l
e( i<=mi d&&j<=r i
ght )
{
i
f(a[i]<a[ j]
)
{
t
empAr ray[i
ndex++]=a[ i++]
;
}
else
{
t
empAr ray[i
ndex++]=a[ j++]
;
}
}
whi l
e( i<=mi d)
tempAr ray [i
ndex++]=a[ i++];
whi l
e( j<=r ight )
tempAr ray [i
ndex++]=a[ j++];
for(i
ntk=0; k<i ndex; k++)
{
a[k+lef t]=t empAr ray [k];
}
r
eturn;
}
}
91

Pr
ogr
am:
Sour Mer
ceCode: geSor
t.
jav
a
i
mpor
tjav
a.i
o.*
;

cl
assMer
ge

publ
icst
ati
cvoi
dmai
n(St
ri
nga[
])t
hrowsI
OExcept
ion

Buf
fer
edReaderi
n=newBuf
fer
edReader
(newI
nput
Str
eamReader
(Sy
stem.
in)
);

i
ntnumber
_of
_el
ement
s;

Sy
stem.
out
.pr
int
ln(
"Ent
ert
henumberofel
ement
s")
;

number
_of
_el
ement
s=I
nteger
.par
seI
nt(
in.
readLi
ne(
));

i
ntar
ray
[]=newi
nt[
number
_of
_el
ement
s];

i
nti
ter
;

Sy
stem.
out
.pr
int
ln(
"Ent
ert
heel
ement
sonebyone"
);

f
or(
it
er=0;
i
ter<number
_of
_el
ement
s;i
ter
++)

ar
ray
[it
er]
=Int
eger
.par
seI
nt(
in.
readLi
ne(
));

/
*Cal
li
ngt
hisf
unct
ionssor
tst
hear
ray*
/

Mer
geSor
t(ar
ray
,0,
number
_of
_el
ement
s-1)
;

f
or(
it
er=0;
i
ter<number
_of
_el
ement
s;i
ter
++)

Sy
stem.
out
.pr
int
(ar
ray
[it
er]
+"\
t")
;

publ
icst
ati
cvoi
dMer
geSor
t(i
ntar
ray
[],
intl
eft
,intr
ight
)

i
ntmi
d=(
lef
t+r
ight
)/2;

i
f(
lef
t<r
ight
)

/
*Sor
tthel
eftpar
t*/

Mer
geSor
t(ar
ray
,l
eft
,mi
d);
92

/
*Sor
tther
ightpar
t*/

Mer
geSor
t(ar
ray
,mi
d+1,
ri
ght
);

/
*Mer
get
het
wosor
tedpar
ts*
/

Mer
ge(
arr
ay,
l
eft
,mi
d,r
ight
);

publ
icst
ati
cvoi
dMer
ge(
intar
ray
[],
intl
eft
,intmi
d,i
ntr
ight
)

i
ntt
empAr
ray
[]=newi
nt[
ri
ght
-l
eft
+1]
;

i
ntpos=0,
l
pos=l
eft
,r
pos=mi
d+1;

whi
le(
lpos<=mi
d&&r
pos<=r
ight
)

i
f(
arr
ay[
lpos]<ar
ray
[rpos]
)

t
empAr
ray
[pos++]=ar
ray
[lpos++]
;

el
se

t
empAr
ray
[pos++]=ar
ray
[rpos++]
;

whi
le(
lpos<=mi
d)

t
empAr
ray
[pos++]=ar
ray
[lpos++]
;

whi
le(
rpos<=r
ight
)

t
empAr
ray
[pos++]=ar
ray
[rpos++]
;

i
nti
ter
;

f
or(
it
er=0;
i
ter<pos;
iter
++)

ar
ray
[it
er+l
eft
]=t
empAr
ray
[it
er]
;

r
etur
n;

}
93

HeapSor
t
Gi
venanar
rayawi
thnel
ement
s,t
heheapsor
tal
gor
it
hm canbeusedt
osor
tai
ntwophases:
I
nPhase1,
bui
l
daheapHusi
ngt
heel
ementofar
raya
I
nPhase2,
repeat
edl
ydel
etet
her
ootel
ementoft
heheapf
ormedi
nphase1.
I
namaxheap,t hatwehav ediscussedsofar,weknowthatthel ar
gestval
ueinHi salways
presentatt
herootnode.Soinphase2,whentherootel
ementisdeleted,
weareactuall
ycol
lect
ing
theelementsofaindecreasi
ngorder
.Letushavealookatt
healgorit
hm ofheapsortasbel
ow.
Al
gorit
hm
Heapsort
(ar
r,n)
St
ep1: Start
St
ep2: [bui
ldheapH]
Repeatf ori=0ton- 1
Calli
nsert_heap(ar
r,n,
arr
[i
])
[endofl oop]
St
ep2: [Repeatedlydeletetherootelement]
Repeatwhi l
en>0
Calldel
ete_heap(ar
r,n,
val)
Setn=n+1
[Endofl oop]
94

St
ep3:St
op

Pr
ogr
am:
publi
cclassHeapSort
{
publi
cvoidsort
(i
ntarr
[]
)
{
i
ntn=ar r
.l
ength;

f
or( i
nti=n/2-1;i>=0;
i--
)
heapi
fy(
arr
,n,
i);

f
or( i
nti=n-1;i
>=0;i
--)
{
i
nttemp=ar r[
0];
arr
[0]=ar r
[i
];
arr
[i
]=t emp;
heapify
(arr,i
,0)
;
}
}

v
oidheapify
(intar
r[
],i
ntn,
inti
)
{
i
ntlar
gest=i;
i
ntl=2*i+1;
i
ntr=2*i+2;

i
f(l<n&&ar r
[l
]>ar
r[
lar
gest
])
l
argest=l
;

i
f(r<n&&ar r
[r
]>ar
r[
lar
gest
])
l
argest=r
;

i
f(lar
gest!=i)
{
i
ntswap=ar r[
i]
;
arr
[i
]=arr[
lar
gest]
;
arr
[l
argest
]=swap;

heapi
fy(
arr
,n,
lar
gest
);
}
}
95

st
at i
cv oi
dprintArray(
intar
r[]
)
{
i
ntn=ar r
.l
engt h;
for(i
nti=0;i<n;++i)
System.out.pri
nt(ar
r[
i]
+"");
System.out.pri
ntln(
);
}

publi
cst ati
cv oi
dmai n(St
ringargs[
])
{
i
ntar r
[]={12, 11,13,5,
6, 7}
;
i
ntn=ar r.
length;
System.out .
print
ln(
"ARRAYELEMENTSARE:
")
;
pri
ntArray(arr
);
HeapSor tob=newHeapSor t(
);
ob.sort(
arr);

Syst
em.out.
pri
ntl
n("
SORTEDARRAYELEMENTSARE:
")
;
pr
int
Arr
ay(arr
);
}
}

Sear
chi
ng:
Sear
chingmeanst ofi
ndwhet herapart
icul
arvalueispresenti
nanarrayornot.I
fthev alueis
pr
esenti
nt hearray
,thensearchi
ngissaidtobesuccessf ulandthesearchi
ngprocessgivest he
l
ocati
onoft hatval
ueIthearray.However,ift
hev aluei
snotpr esenti
nt hear
ray,t
hesear ching
pr
ocessdisplay
sanappropri
atemessageandi nthi
scasesear chi
ngissai
dt obeunsuccessful.
Ther
ear
etwopopul
armet
hodsf
orsear
chi
ngt
hear
rayel
ement
s:l
i
nearsear
chandbi
nar
y
sear
ch.
96

Li
nearSear
ch:
Li
nearsear
chi
sal
socal
l
edsequent
ialsear
ch,i
sav
erysi
mpl
emet
hodusedf
orsear
chi
ngan
arr
ayforapar
ticul
arval
ue.I
tworksbycompar
ingthevaluet
obesear chedwit
hev er
yel
ementof
thear
rayonebyoneinasequenceunti
lamatchisfound.Li
nearsear
chi smostl
yusedt
osearch
anunorder
edl
istofel
ements.
Forexampl
e,i
fanar
raya[
]isdecl
aredandi
nit
ial
i
zedas,
i
nta[
]={
10,
8,
2,
7,
4,
9,
1,
6,
5};
andt
hevaluet
obesearchedisval
ue=7,
thensearchi
ngmeanstofindwhethertheval
‘7’
ispr
esent
i
nthear
rayornot
.Ify
es,theni
tret
urnst
heposit
ionofit
soccur
rence.Her
e, pos=3.
Thebel
owal
gor
it
hm i
sforl
i
nearsear
ch.
St
ep1:St
art
St
ep2:I
nit
ial
izesetpos=-
1
St
ep3:I
nit
ial
izeseti
=0
St
ep4:Repeatst
ep4whi
lei
<si
ze
St
ep5: I
fa[
i]
=val
uet
hen,
Setpos=1
Pr
intpos
[
Endofi
f]
Seti
=i+1
[
Endofl
oop]
St
ep6:i
fpos=-
1then,
Pr
int“
val
uei
snotpr
esenti
nthear
ray

[
endofi
f]
St
ep7:Exi
t
I
nst ep2and3oft healgori
thm,weini
ti
ali
zethevalueofposandi .Instep4,awhilel
oopis
executedt hatwoul
dbeexecut edunti
lii
slessthann.Instep5,acheckismadet oseeifamatch
i
sf oundbet weenthecur r
entarrayel
ementandv al
.Ifamat chisfound,thentheposi
ti
onofthe
arr
ayel ementispri
nted.
Thef
oll
owi
ngcodei
mpl
ement
sli
nearsear
ch.
Sour Li
ceCode: near
s.j
ava
i
mpor
tjav
a.i
o.*
;
cl
assLi
near
s
97

{
publ
icst
ati
cvoi
dmai
n(St
ri
nga[
])t
hrowsI
OExcept
ion
{
Buf
fer
edReaderi
n=newBuf
fer
edReader
(newI
nput
Str
eamReader
(Sy
stem.
in)
);
Sy
stem.
out
.pr
int
ln(
"Ent
ert
henumberofel
ement
sinar
ray
");
i
ntsi
ze=I
nteger
.par
seI
nt(
in.
readLi
ne(
));
i
ntar
ray
[]=newi
nt[
size]
;
Sy
stem.
out
.pr
int
ln(
"Ent
er"
+si
ze+"El
ement
s")
;
f
or(
intc=0;
c<si
ze;
c++){
ar
ray
[c]
=Int
eger
.par
seI
nt(
in.
readLi
ne(
));
}
Sy
stem.
out
.pr
int
ln(
"Ent
ert
henumbert
obeSear
ch"
);
i
ntsear
ch=I
nteger
.par
seI
nt(
in.
readLi
ne(
));
/
/sear
chi
ng
i
ntcount
=0;
f
or(
intc=0;
c<si
ze;
c++)
{
i
f(
arr
ay[
c]==sear
ch)
{
Sy
stem.
out
.pr
int
ln(
sear
ch+"i
spr
esentatl
ocat
ion"
+(c+1)
);
count
++;
}
}
i
f(
count
==0)
Sy
stem.
out
.pr
int
ln(
sear
ch+"i
snotpr
esenti
nar
ray
.")
;
el
se
Sy
stem.
out
.pr
int
ln(
sear
ch+"i
spr
esent"
+count
+"t
imesi
nar
ray
");
}
}
Out
putCode:
Ent
ert
henumberofel
ement
sinar
ray
7
98

Ent
er7El
ement
s
2
3
1
2
9
2
4
Ent
ert
henumbert
oSear
ch
2
2i
spr
esentatl
ocat
ion1
2i
spr
esentatl
ocat
ion4
2i
spr
esentatl
ocat
ion6
2i
spr
esent3t
imesi
nar
ray

BinarySearch:
Binarysear ch i s a sear ching algorithm thatwor ks ef f
icientl
ywith a sorted li
st.The
mechani sm ofbi narysear chcanbebet terunderstoodbyananal ogyofat el
ephonedi rect
ory
.
Whenwear esear chingf orapar ti
cularnamei nadi r
ector
y ,wef irstopenthedirect
oryf r
om the
middleandt hendeci dewhet hertol ookf ort henamei nthef ir
stpar tofthedirect
oryori nthe
secondpar toft hedi rectory.Agai n,weopensomepagei nt hemi ddleandthewholepr ocessis
repeateduntilwef i
nallyf i
ndt her i
ghtname.
Inthisalgorithm,weseet hatbegandendar et hebegi nningandendi ngpositi
onsoft he
segment .Midi scalcul atedas( beg+end) /2.Theal gori
thm wi l
ltermi nat
ewhena[ mid]=val
.When
thealgorit
hm ends, wewi ll
setpos=mi d.
Howev er,ifvali snotequalt oa[ mid],thenthev al
ueofbeg,endandmi dwi l
lbechanges
dependingonwhet herv ali
ssmal l
erorl argerthana[mid].
a)Ifval<a[
mid]
,thenvalwi
l
lbepr
esenti
nthel
eftsegmentoft
hear
ray
.So,t
hev
alueofbegwi
l
lbe
changedasend=mid-1

b)Ifval
>a[
mid]
,thenv
alwil
lbepr
esenti
nther
ightsegmentoft
hear
ray
.So,t
hev
alueofbegwi
l
lbe
changedasbeg=mi
d+1

Now,letusconsi derhowt hi
smechanism i
sappli
edtosearchf oravalueinasort
edar
ray
.
Consi
deranarraya[]thatisdecl aredandini
ti
ali
zedas,
i
nta[]
={1,2,
4,
5,6,8,9,
10,15,20} ;
andthevaluetobesear chedi nval
=8.Thealgor
it
hm wi
ll
pr ocessedinthefol
lowi
ngmanner
.
Beg=0,end=9,mi d=(0+9)/2=4
Nowv al=9,anda[ mid]
=a[ 4]=6
a[
4]islessthanv al
,therefore.Wenowsear chfort
hevalueint hesecondhalfoft
hear
ray
.
99

Sowechanget hev
aluesofbegandmi d.
Now, beg=mid+1=5,end=9, mid=(5+9)
/2=7
val=9anda[mi d]
=10.
A[7]islessthanv al
,there,wenowsear chfort
hev
aluei
nthesecondhal
foft
hesegment
.
Soagai
nwechanget heval
uesofbegandmi d.
Now, beg=mid+1=9,end=9, mid(8+9)/
2=8
Now, val=15anda[ mi d]
=15.

St
ep1: st
art
St
ep2: Setbeg=0,
end=si
ze-
1,pos=-
1
St
ep3: Repeatst
ep4,
5whi
lebeg<=end
Setmi
d=(
beg+end)
/2
I
fa[
mid]
=sear
ch
Setpos=mi
d
Pr
intpos
[
endofi
f]
El
sei
fa[
mid]
>val
Setend=mi
d-1
El
se
Setbeg=mi
d+1
[
endofi
f]
[
endofl
oop]
St
ep6: i
fpos=-
1
Pr
int“
val
uei
snotpr
esenti
nthear
ray

[
endofi
f]
St
ep7: End

i
mpor
tjav
a.ut
il
.Scanner
;
cl
assBi
nar
ySear
ch
{
publ
icst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
i
ntc,
fir
st,
last
,mi
ddl
e,n,
sear
ch,
arr
ay[
];
 
Scanneri
n=newScanner
(Sy
stem.
in)
;
100

Sy
stem.
out
.pr
int
ln(
"Ent
ernumberofel
ement
s")
;
n=i
n.next
Int
();
ar
ray=newi
nt[
n];
 
Sy
stem.
out
.pr
int
ln(
"Ent
er"+n+"i
nteger
s")
;
 
 
f
or(
c=0;
c<n;
c++)
ar
ray
[c]=i
n.next
Int
();
 
Sy
stem.
out
.pr
int
ln(
"Ent
erv
aluet
ofi
nd"
);
sear
ch=i
n.next
Int
();
 
f
ir
st=0;
l
ast=n-1;
mi
ddl
e=(
fi
rst+l
ast
)/2;
 whi
le(f
ir
st<=l
ast)
{
i
f(ar
ray
[mi
ddl
e]<sear
ch)
f
ir
st=mi
ddl
e+1;
el
sei
f(ar
ray
[mi
ddl
e]==sear
ch)
{
Sy
stem.
out
.pr
int
ln(
sear
ch+"f
oundatl
ocat
ion"+(
middl
e+1)+"
."
);
br
eak;
}
el
se
l
ast=mi
ddl
e-1;
 
mi
ddl
e=(
fi
rst+l
ast
)/2;
}
i
f(f
ir
st>l
ast)
Sy
stem.
out
.pr
int
ln(
sear
ch+"i
snotpr
esenti
nthel
ist
.\n"
);
}
}
101

1.Whati sanabst ractdat at ype?Di f


f erent i
atebetweenl inearandnon- l
ineardatastructurebytaking
twoexampl eofeach.
2.Whatar et hespar semat r
ices?Ment iont woofi tskindsanddi scusshowt heyar estoredinmemor y?
3.Di scusst headv ant agesanddi sadv ant agesofl inkedl i
stov erar raysandwr it
eanal gor
it
hm tofind
outthesecondmaxi mum el ementi nar ray.
4.Wr i
teanal gori
thm t oper f
or mt her angeofoper at i
ngonal inkedl i
st .
5.Whati smeantbyt reetraversal?4M
6.Whatar et heproper ti
esofabi naryt ree?12- Mar4M
7.Descr ibet heal
gor ithm forbubbl esor tandsel ect ionsorttechni ques.12- Jul15M
8.Di scusst hepur poseofl i
nkedl i
sts.Al sodescr ibet heoper ationsper f
ormedonal inkedli
st.12-
Jul
15M
9.Descr ibet hebasict erminologyoft reesandgr aphs.12- jul4M
10.Wr i
teanal gori
thm f orinsertionsor t.
11.Wr i
teapr ogram inJav atoi mplementdoubl ylinkedl istsMar 15- 15M
12.Explai
nt hediff
er encebet weensi nglel inkedli
standdoubl yl inkedl i
st.Jul-
13,7.
5M
13.Wr i
teaJav apr
ogr am toimpl ementci rcularqueue.Mar -
13, 7. 5M
14.Wr i
teaJav apr
ogr am tosor tagiv enl istusingbubbl esor t
?Jul -13, 7.
5M

UNI
T-I(IntroductionandLi nkedLi st)
1. Explainaboutpr imiti
veandnon- pri
mi ti
vedat astructur
es.5M 2018
2. Whatar esparemat ri
ces?Expl ai
nt hem.
3. Whati sLinkedLi st
?Expl aindi
fferentTy pesofl i
nkedl i
stindatastr
uctur
es.
4. Whati sLinkedl ist?Writeaboutal lpossibleoper ati
onsonsi nglel
i
nkedlist
.
5. Wr i
teadv antagesanddi sadvantagesofsi ngleli
nkedl i
st/Linkedli
st.
6. Whati sdoubl elinkedlist?Wr i
teitsadv antagesov ersinglel
inkedli
st.
7. Wr i
te
7. Whati scircularlinkedlist?Writeapr ogram toexpl ai
nt heconceptofcir
cul
arl
i
nkedl
i
st.
8. Wr i
teaboutdi fferentappl i
cati
onsofl inkedl i
sts.
UNI
T-IIStackandQueue)
102

1. Whati
sstack?Wr it
eitsADT?  Explainv ari
ousr epresentati
onsinstack.5M 2018
2. Wri
teaprogram toexplai
nbasicsoper ati
onsofst ack.
3. Wri
teanalgorit
hm andexplai
nhowt oconv ertaninfixexpressi
onintopostfixexpressi
onusingst
ack.
4. Whati
sQueue?Wr i
teitsADT?Expl ainvariousrepresentati
onsofQueue.
5. Whati
sQueue?Expl aindif
fer
entty pesofQueuesav ail
ableindatastruct
ures.
6. Whati
sCircularQueue?Wr i
tealgorithmst oinsertanddel eteanelementfrom cir
cularQueue.
7. Whati
sCircularQueue?Wr i
teapr ogr am toexplainitsoperati
ons.
8. WhatisQueue?Wr iteaprogram toi mplementQueueusi ngarr
ays.

 
UNIT-
II
I( Trees)
1. Whati sBi naryTee?Wr itepr opert
iesandt erminologyofBinaryTree.5M 2018
2. Explainv ari
ousr epresent at
ionsofbi narytree.
3. Writ
eaboutdi f
ferentt r
eet r
av eli
ngt echniquesandal sowrit
ealgori
thmsf oreachtravel
ingtechnique.
4. Writ
et hepr ocedur eandexpl ainwi t
hanexampl ehowt oconstr
uctBinar
yTeef rom it
sTr av
els.
5. Explainabouti mpl ement ationofBi naryTr ee.
6. Whati sBST?Howt oi t
sdi f
fersf r
om Bi naryTr ee?Wr it
eabouttwopossiblerepresentat
ionsofBST.
7. Withanexampl eexpl ai
ni nserti
onanddel et i
onofel ementsfrom BST.AlsoWr i
tealgori
thmsf orsame.
8. Whati sThr eadedBi naryTr ee?Expl ain.
9. Whatar eHeapTr ee?Expl ainHeapsor twithexampl e.
10.Explaindi f
ferenttypesofBi naryTreeswi t
hexampl e 

UNI
T-I
V(Gr aphs)
1. Whataret headv antagesanddi sadvantagesofGr
aphs.5M 2018
2. Expl
ainin-order,
pr e-
orderandpost -
order5M 2018
Wri
teaboutvariousGr aphTr aveli
ngTechni ques.
2. Howt ofindaNodei naGr aph?Wr it
eaboutbasicsear
chingtechniqueswi
thpr
ogr
ams.
3. Whataret hev ar
iousway stofindMi nimalSpanni
ngTree?Explai
n.
4. Expl
ainTopol ogi
cal sortwi t
hexampl e.

UNI
T-V(SearchingandSor t
ing)
1. WhatisSearchi ng?Explai
nLinearsearchwithexample.
2. WhatisSearchi ng?Explai
nBinarySearchwi t
hexample.
3. WhatisSorting?Explaindif
ferentsorti
ngTechniques.
4. Expl
ainQuicksor ti
ngTechniquewi thexample.
5. Expl
ainsel
ect ionsorti
ngTechniquewi thexample.
6 Explainbubbl esorti
ngTechniquewi thexample.

DATASTRUCTURESUSINGJAVALAB
1.Wr
it
eaProgram t
oimplementt
heLinkedLi
stoperat
ions
2.Wr
it
eaProgram t
oimplementt
heStackoperat
ionsusinganarray.
3.Wr
it
eProgr
amst oimpl
ementtheQueueoperat
ionsusinganarray.
4.Wr
it
eProgr
amst oimpl
ementtheSt
ackoperati
onsusingasinglyli
nkedli
st.
5.Wr
it
eProgr
amst oimpl
ementtheQueueoperat
ionsusingasinglyl
inkedl
ist
.
103

6.Wri
teaprogram f
orarit
hmet i
cexpressionevaluati
on
7.Wri
teaprogram t
oi mplementDoubl eEndedQueueusi ngadoublyli
nkedl
ist
.
8.Wri
teaprogram t
osear chanitem inagivenl
istusingLinearSear
chandBinarySear
ch
9.Wri
teaprogram f
orQuickSor t
10.Wri
teaprogram forMergeSor t
11.Wri
teaprogram onBinarySearchTr eeoper
ations(i
nserti
on,del
eti
onandtr
av er
sal
s)
12.Wri
teaprogram forGraphtr
av er
sals.

You might also like