sh Module -3
Greedy M etbed
ie as a problem solving technique thal
al usays dries do find th best solutiom dhak
poorks an stoge considering m2 input ob a
dime sith he hope to geb on optimal Solution
the chosceprade rnust be
- deostb)e - th has do satisfy the problen 's
ceonstraink
- optimal - id has fo be the best fecal choice al¢
Aeasible choices Bole 2 ikon olen
. ( maximizes the profit or mind mige Th less)
waade, xf cannot be changed
~ tyvevocable- once
a subsequent chkeps ef dhe algorithn.
Adgorith Greedy CA,n)
WA ks adest of nm anputs
solution = b
der feo te n-t
{ x > sebeet (0)
#4 (feasible (sel uh'on , x))
4 Sateen = Unters dation, x) :
ai
retaon sol uct fn
athe three dunckion used in alg orl an are.
select) cedacta the next taped from he dist
a assigns it to %
= deastble (9 - chicka whetlur celecked input x
con be inserted wette parttal seubin.
or rot 2-Unim(>- 14 selectim of £ resulh in deasite
soluhiinm , kt fh added to the solutfom using
Vain function . Otarwese st ts not added
The various algorithms thal use the correept af
greedy approach are
-Dijkstrars alqorithar so find th shortist
distance frome source do destivobtan .
— Prémnrs algorithm to find The minmimuwe
spanning tree
euskal algorithm de find Fhe miniruunr
spanning tree
_ Hud fran coding for dala compression f
avery phion .
-~ Coin chang problinr
knapsack Pore dele we
Lyiven a knapsack ef capacity M and
nr objects od wserg hls Gor, a 940g +1 Wn coIth” profits
Bea pre oe cee Me ea) oe the -Pracktons
of th objects that are added inte the knapsack, —
the objecd Sve us to place objects inf us LY
knapsack with maximum prot and cout ghls op
objects chosen should not xxceed the capadlhy
of — Knopsack
Moximnige Sy Pe
ast
Coustraiud DB wits
re) break
xCrje!
Cc ere -wf{ij
aud for
if (f<=n)
7 x Ctl = ve/olet
evd if
Preblemt- Fand an opkimal solution Lo Hee lenapsac
instance N=4, mer !5
(py Ps Pas Pur Ps Por Pa = (10,516 36,18 53)
(v9) 1 » 3 JUD y Hg 499,498 )=(2,3,5, 41,4, 7
Sotutem- Capacly od the knapsack | Mets
Ntunber of chjects, nit
Progets Ch es Pu, Puss Ps » Po ,Pa)= (10,8, 15,7 6) '83)
rateradnts (v9, \eDg BOs $n bDe 49g, 2 (213157, ts)
_-Unimey. 14 selects od X resulb in easite
solubion , % L added sto “the solukfo using
Vaim funchion . Ofirusese af as not added
The various algorithms thal use the trarcept
greedy approach are
-Dijkstrars algorithu to find athe shortes$
distance from source to desttuohiar.
- Proms algorithm to find The mintimune
spanning tree
— kruskales algorithan ds dind the miriruuns
spanning tree
_ Huffman coding for dala conspress ton =
sncruption .
- Coin change problns,
keapsack “Pow debe wr
piven a knapsack ef capacily mM ani
a objects of wetghls sr, W) 004. Wy cot H profits
Pro Po» Pp --- Pa. Let x,y x2, Xa:-. Xm be the Prachions
of oth objects thot are added tate th k napseck
aie objective us cto place objects info I
knapsack with makimum profit and coecghls op
objects chosen shoutd not exceed the cappactl e
of Knopsack
Maximize ‘Dp Pky
eh
Corttraiud > wuira re) break
xtr]st
ve ere -wft]
aud for
irc)
e x te re/o ly
end if
Preblemr- Fund an optimal solution fo We knapsech
Enstance N=4, m=z 15
(py + Pas Par Par Ps 1Pe» Pa)> (10,5515 ,4,6, 18,3)
(eo, 5 Wy , WS pW Wg 4% ,429)=(2,3,5,4,1,4, ()
Soludsm~ Capactly of “the knapsack M=15
Ntuncber of chjects, nit
Propels (P,) Par Ps PusPs , Pe, Py) = (10,5,15,4,6, 18,3)
Werghts (09) U4 65 $0 Ogg 494) = (2.3/5.9, Ute)Te get optimal
Poo te ©
Ty es
Pees
v2 73
Ps 15 3
cose
feos hy
Wy cag
fo ee
5 :
Poo. W8 = 45
Oe y
Bit 32
ay
Arrawg Px feos
6>F>4U-5 >3>3>1.69 >]
(prdik)G 10 18 15 3
3
(-deeghts) | ay 5 | 3 3
(Objecks) 1 2 3 4 p
Ss 6
ct
rc
Solitinn Ps fuoe
in clereasng oades
object wos | Pe | X21 o FC | “Probl =x a Pp FC TC WORX
aikd = [
1 iy ie ' | IKE SG = ISH 1x1
ee a ee aly
a to | TxtO = to = 1-21
eee ee L = 2
3 yu otg 1 rics = 12-U |
| | |
=8ffs pr [rer or 2S Profits te Py) Ce ve -wor et
eee wot
uy 5 6 | I tetsstS (= 8-SHt
as ft sa | =o
5 | | 3 I (Tk 3 =3 =a-1*]
— ft | =a
| : _
6) 3) 5 4-064 oss: =3.35) = 2-3" 0.69
cm SSS +H ve
4] 4
+—__| 4
|
Peale te C+OF 18 $154343.35 = 55.5
Prachton (2%. )Xs 4, x X56 %e Xa) = (1,1,1,1,1,0,64,0)
Insights Coos 9, , wy Oy 16/404 S8a) = Goa, 5,1,3,4)
ere ™ =a0
ne3
Cp,,Ps> Ps) = C25,04,15)
Cus, 09, 695) = (18,15, 10)
Te ged optewa colutrm — Pr]ude
Plas
ae (EE 138
ee ee
WO. 15”
Arrange on Olcreasing order
1.6 > 1.5 S 1.38
Prodals - gy 1S os
Weights - 5 to tg
Objects- 4 2 3TCO Tc ~ wk gw
ctntial fo > -
. 7 . *iG0
' Is ay i Veo sou > 2O-1IS #]
——___ 5 a
0} 15
2 |! \ To 78 [OSS 248 2s _ pes
a |
et)
3 ee 25 Oo
=f] PF} o
Profets - 4 +4+4.52 316
Pein C¥ 11% 1 %s)= (C1,0.8,0)
Weaghis 7
gqhas Correos, 495) > (15, 10,18)
Yob Sequrnctug wilt dradtitus
Geven set of vn febs avd assockaled rH
deadtsne dy >= 0° auc)
fs required be Pind 4h, ih
add dhe chosen frbs should
cUlate chadtines 4 ty
be mrontuuum cot Me
antheger
each je tia an
prefat p,rro, ot
of ftbs such that
be complelkd — wsithin
profit tarned should
fotlowing contbrarnet
~Ouby ow wmachini ds availabh fer Processing 4s
~ Ovdy ou 3% must be proussed ak any Poin q
time
~ A 4th 2x said do be cowplited af at as
proussed om a wachin for or aol ct dime
woth cradlenes
filgenithu for tl je Sequtmetug
Akgqorith ux Greedy seh Seqrunctug (4,4 ny
// Laput - no number of sebs
A- tD Array
/7 Output - ,~ sel of n jobs te be lected
s within their deadlines
?dole jlele—o
fe 403
k=}
dor aerh n
{
week
whole (4022 < AGECS) ond dffacrd!-*)
yvrer-t
} )
eC aCer>= AG OC) and slrl> x)
fer qck deum to r4I
ifq+] =jly]
eud fer
j&td-4
ke ket
s
- retura k
Eqr- Obtarn fe optrm al solctim for te jel
heqmencing oproblis wort: daactins whire ney
prodils Cpr Pas Ps, e4) = (too, 10 15 24) owe!
duadtines (di ,do ida, da) = (2,2,1)
Qy evens so Palace) nd
Pz 100 | 10 | iS 24
id. |2 2 |
Co | |. " Hreromge jobs in decreasing order f profile
aT . a &.
[pz | wo] 2a] is [te |
a2) ti zit
ple feet Ct loce die
r oo A gchs xe AS
a {2 | | + — Profit = 100
chep? - gen, Pert, daz)
4 +t jhe seh
TLe
~ Pweg ve 94 41005124
7
a{t [a
cs alll discarded as the duadties
ane Over
Optimal Sobre = £2, 14
Total Prodst = er t100 = 124
Ey, ee yee Walls
123 4 60| loo] 20] yo, 20 7
lap 2 tS 4! |
Arrange ou decreasing ordir of profak
a | tf 3 ye s |
p, |100 | O40 20 20}
ry, |l2|2{3]! |
cee | | | |
shept- iets Pre drt
= 100,
ee
aT a: {i}
alu =e Profil = 100“i
Step2- iz2, Py=¢o, de=2
B34 €
TE os: het
| Profit = 100460 -160
u
PIP ip
steps- 223, Pesyo,derr
Discarded
step wath, Pi-20 diz
1203 4
sft jo] | yeft,2,3
a i 213 Profats = 100+ 60420
= 180
shepy= To. Piz20,der3
discarded
Oplimal Selutuin s Jr,o dy
ciotal: Cretats = go
E93 - Wit
copy)e (315,26) 18.14 6,39)
(Ps Po --
m Cdy da eeeda)® (1, 3,4 3,2,1 2)
River, [fF
_Rrrange J
aa
[@ [| 30arp fel, Peco it &
J 2 3 u S
= T {
! Teds}
dla +E Profit =30
Shep> = 422, py z20, dizy
fo2 3 & 5 EF
aii f2 sz fr,2}
afo[y |
Prodi < 20420-S0
se! 2 +E
7ERP x =41,3,2}
de fal4 Profit =30420 418
= 68
stepy = gsh, Ppe6,dr= 1
\ 23 & 5 6 OF
7 BE BP sz 4u,1,3,25
d bets] 4 Profst < 64304 20+1¢
Ral ef te {cbs are chivcordd #4
Opkrwal Selutronr = { ats 82h ~
Tetel Prodot = 44
Deryketrars A lqoatthur (Samgl- Source Shoukel-
\ Path wr)
To find the shortest decdauce froma gen
verix te atl ottar vertrees © this
probln an
| not dedimad for nigative nuubers .
a—pitkstears olgouithu dor Aingl Aourct shovtusl
Vuctane qeeblen “
Algortthur Dipkaba( nes, sored)
Jf te compute the shortssk oliatance drome source
te destenotion
Je Tapet . o> muwber of verdrces
wo- Cost adjacency watery
Source - Source vertx
77 owtpak » d- shortest drsdance fronr source Os
all otter nods
s- gives the nodes vesiked £ not vasiled
t- 446 do n-t deo
- die cost Csoure, £)
s[4le—o
eud for
s[sourct] eI
dor ie) ke n-i do
Con te esl Be ded eco
£ u€v-s
add ute S vey sfule|
for ever veEV-S do ( veo de n-t)
a4 (d Cod + olay) 09
‘SB Ionia (vo s.t19)=24 6) 2,24
ACAD 5 min(d0,14+29)= 34
a fo
5,3,1,2 0,4 Ale}e min(vo,29+20)= 44
© 434
dfy]=rmin( 3h, 24400) 237dl i = oO
5,31,2, be © AO = min (4a sues) 4 eee
531M - | a
@, 60
d[oJ= two | ow | 4d] 44
ADD =o fp | te] tay | 4
d(ay=% |e | oq Jaq | og
d Tale & | it a | 4
ot tujee [3q [34 ] 3h 34
d{5)-0 lo |° 6 | 6
bo, chorhask clithans from Soto all other nate
cfaalyais ~ Tore Gophers ty of Dajkatrers olgoatthrs
wo gl-B)
fro
- BE (eo-e (n-0-049)
>
= on Bl
—~—~=£&*~—iSE=
~- Ag a se -= an(n-| -141) ad
= 2n(n-1)
= Qn? nw
ie.
know, &= (VE)
Daiskstrars algorithr so tind ahowtsl- diclance
aud chorksb path teu ~ source te dishtralin
flgorithm —Duyhsra Criw, source, destrnotio
Sp)
// Purpose- To oupule We ahorlst olistance
shorfist path from source de dastinction
en
We Lon as the number of
verkice
and
yp Laput- n-~ Number of verties
ws. Cosk adj acencey mn at hiX
Meee oce cutie
dechindlev ~ destination verte
ye Ovtpukb - d- shortest distance trom source fs
all nodes =~
p-shortist path from source te destin |
t
ration
g. node& vasilid
dor ieo bk n- de
not veut
dAte]- coat (source, <]
ptta = Source
st) = 2
eud dor
sEsourcel
nFind ui avd dfa} such Ahot dfuy ws minimum +
uév-s
add u &S
ad (us des Hiunaten ) break
dor avery ee h,rrrrrlclr es)
af (d 001+ wl, v9 <¢dcvq7)
Atv) =d fut wlu,v)
piv ru
eu of
sed oo
end = Aer
Ex. Fund th shoriest distance aud shortisk path
PH
from verdex 5 fo verlix O
20 bo ‘oo
Oo 3 %
30 0 oO
yw 05 0)1,2,3,4
553 0,1, 2,4
ve VS
Bole pele
553,52 Oy
53524
5,3,1,2,4,0) ~
a
Ao] =o oO
df= 0 ty
dhJ=& 0
ATI=
dti)=-% | 34
a[s}=o0 0
Shortint
| dT w]= min (409, dtc 4 10 C3 Ba) Alyce | util
= } o 34
dtol=min (m,4 +t) = 00
ADJ = min( 0, 4 +O) apy pliq=3
dod = min (oo, +0): ok? lt
dla] = min(po 4435). 34 plu-3
do] =min(vo, 14+ 00) = 60
dt2] =min(oo,14-+15)= 246) pEIe1 | g.2q
STH] = min(vo ly +26) = 34 plud=1
A Lolennin(m 24420244 plo}-a -
ALD = min (34, 24400)= 3g ad
dfel= min (44,3444): 446) = | 0,49
ttc.
me | ud) 44
Me Ay
24 24 4 ~
Bo
Be a
oO Ce oO
dxatance from 5S de O w 44
shortest pathred and ae shordest
asind Dajkatras
ue
dastance {roms Source a
e
a ae =
. oe ES min(ate deo) ualuy
a | - | a oe dion _
ood bjc,e AC] min (0, 442059 :
a | dLe3 =min(o, 44912 @ |"
| dled
min Us atu)
a,d,b ce |d Cc} - aaa are): p2
de:
a
@
d({aj-o ® °
d(bl-% 4 q
dCe]en jlo |i
d{dj-4y | +
ACe]-% \% 60
min cn a +m) = ro
CFO
a,d,b,¢| @ [aCe min Cea , nadars © 2,18
c,Id
Path ftw aceShordest
pe Xo
to
~to
to
bo
to
distance
a-=0o
b-q
c=la
ct ao
ee
frome aA panntn “Tree
(EU as a lyee in usbich ad) neoded are
conected coithout Aorming a closd path
a po (0) 2° 4;
it
N-nodes have n-[ eclges in Apanning tra
[Link] Sp anni "q tire
Ik 22 o tree un clack of) nodes are
“connected witthouk forming a closed poth,
hese coal is minimum -
“Préms Al Igostthnr
urd te fand th minimum span)
cree of a given graph:
Algorithm Proms (nw)
~// Purpoke - “To alt tHe indi nae
com p: minimum spa ar]
(1 Tnput ~ a- no. vertices
«d- Coat adjacency matetx
// Outpul - Spanning lree
Shept - Cobtarn an adge orth stuast cost atom Ihe
adjace ney wm atn'x)
mine 4999
Souraeoo
for ic-o fe n~l do
-for ee bon -t do~4
i («CICj3! <0 44 aCeIL fl cz min)
min © afd G3
Source 4
eud af
tud Jor
end dor
step2 - Cinthia lisabiin to find minimum open
sree]
tor bo to n-1 do
SfiJeo : :
dCi wlsource a ]>
ply Aource
cud -f or
step a- ( Fad wininuin Apanning tree]
S[kource) — 1
gbumeo
koo
dor key ado n-t do
Find a aud atu)
Add uh S$
Sdeck an tdlge with Bost cock
Add coak of ccbobid «
for ave veV-S do
2 t (CoCavy ( I(Cn-= + 1)+(Cn- v- -0+1)|
= es an
i=l
= an(n-1-14))
= rn(n-1)
ne ae
£(n) = n> n= tv
Time comple 4 o( vet)Find the minimum Spanning free for the
follous; a) neh
60
0(o,0) 54 1 (0,60) i 2(0,10) BGS C0, —) 2
5(0,-) ae .
2 (0,10) =, 3(2,-) , 4(2,-) , $ (2,50), 1(0,60)
5(2,50)=s 3(5,80), 4 (5,30) , 1(0,60)
u(s,30) —s 2(s,e0) , (4, 40)
(ys aChee) See ae
site i
Spanni ng Lree 14
to ~ we
@ |
50 30
@)
alike wt of Spin Gee as ° a
bk: Sages peer ee ie aaws 2) Fino Wh nindnun spanning tree Using
Prime
: QoS (2)
By 6
a(a,o)—s bass) ,¢Ca,-) »A(ast), 2(a,-)
b(a,s) => e(b,1) , d( 3), 2C6,~)
<(b) =S dfb,3), #0c,6)
A(b,s) = 2(d,2)
edb 2)
Sp anning free &,
Coal 4 Spanning tree = S4t+3+2-5,a(a,o) => bla,3) , ¢(b,4), dCb,-) 402.6), 44,4)
e(b yay des) ,Fe,4), e(a,6)
ge) eles) eae)
e( 4,2) —> 4 (4,5) |
al $5) |
Spanning ree “
Cort od spanning tree =15-
eee, ©
O———®
| Cog ef Spanntug tree =15spanning “Lree
) Use kruskals meth od do find min cost
for ~the below graph
a,b |
ad be } +
re ee
jet | F |
ce | 4 |
be lo |
| Cod ty |
| due t3 |
c.f | re |
e Lee ao |
= find («) | ous of UntnCi, yd
Ea 4e an )} @r) hes ius) cert Ce} CA
a : | a 7 uy
ab | Oo! ab 0 0 8 Ne
boc 0,2 | b,c 0 oO oO 3
, | foo 2 | uw
a re 0 0 0 3 °
a, 0,4 2 | a
| 0,° discard © © © a| a | G2) cel Giese
be | 9° | duscar | 0 0 So
od of fice | © 0 0 0 0
dye | 0,0 | discard | 0 © 0 © O
©
oft | 0,0 |diseard | © © © ©
| 0,0 dustard o © 0 08 0
bd
Spanning tree #28
“Yolal cost <= 84% 45644411 -3q—
& beruskales -AL osdth ww
23 used te Pind Ahe minima Apannlng
tree of a ances greek
Algor ith Kruskal (njm,€)
/VLnpat- n- Ato, of vertices
mo ve 4 dae a .
=e * s on wor ws
// 0 utput - th ea pinning aor
count eo
kao
2 sume—o
for fe-0 to ndo
parent [i Je i
hn Go n- aud € +4)
Sadick au edge (uy) usath Luash wot
we dind(u, pared)
feted (v, parent)
24Catep)
e tLe) DoJe-u
tcf] v
kat
count+ +
sume-Aum + cost(u,v)
Quito. Cay ,parenk )
tcl 4
MW Ddde Wh dae
eud shi )
: w l=n-1
: Cone ' Spanning tree clo not sexist”
vdurnund it
vorite “ Spanning tree 88"
for feo tb n-2 A
ewortte (4 ICD 009)
end for
erie (" cos q spanning tre’, sum)
Algortths Aiud (v, st)
volute (stv! S v)
a =v]
setuon V
and tla spanning brue wing henna bol is alg oie
Edge Coat
0,> |
a
2
3
ty
12 Ss .
5
6
6
64
tefindu) | 9 pe Union (4,4
ea ay ete ah ew C3 04 ed e43 oo)
Oa | 0,2 0,2 | oO 1 Oo 3 as
339) |||) 3.5) 250) | Oo | Oo 3 7 3
Lu ty Ly Oo t 0 3 | 3%
0,1 0,1 0, | 0 0 0 3 13
ae 0,3 ajo o 0 0 0 1 38
LX | 0,0 |Disard 9 © 09 © | 3
as 0,0 Ioiscard o 0 © 013
ayy | 0,0 iDuscord) O O (0 O 1 3
us | 00 laascad|] O © O © | 3
0,3 ©,0 [Deseard | oO ° oO @ | 2
the spanrang hres ek
Cost of 4panning Gree = 343 +144 42 = 12this deals owitth how a Atring or MRE
can be eucoded and clceoded so as to save Lh
apace
The Jno types of 2ucodi
Fined Lagi tacdng “q daha
Vv ¢
- artable deugth enced? “g
Fixed Lengts needing
Te hi bechr¥oue each characliy tn Ua
hick 4s asstgned a of same Length
mydegn , where nt
tn the” fet :
Fer 4q, if the fect 23 “RAMA-RAMAR",
various atphabets in the text are TRE TALS My? =?
vohuich amouvts bo 4: So on oo ey .
m= fog H+ 2a
bie tthrtn
a the number of alphabets
the
Mm R =
goo, 300 ‘00
\o \\
\ characters | A
Frequency | yoo
Fixed Leugth 00
ol
ae Ale Atring RAMA RAMAR
onceodd uring I ode word.
Fo voor cost too 09 100%
Length of hie ching 2h OO bal
Po = 49,659 mi es een 3 bale are srequired
dow eneralin the code word
can be
We ed u-bila are required.YD Versa Legh cucoalg
Arnolter woay of dbbatuiag the boitsbeeam
gs to use shorter codewords or Areqperdly appeareg
characlérs aud longer codewords for Liss frequs
occuring charackernd thus the be ugth of ae sf
stream “for an alphabel 4 sapfesk
For 24,
[chaurackr | A
ee Hae8 Le. fe
TNarsable leg) cl eae = I
Now “the string RAMA-RAMAR can encecteal
using bitatring as
Ctl G00 0 Ol ol IoC No.
wth eX of bat atring #& 1q bseks.
Plgoréthm Huffman — tree ( text a)
41 LInpuls - Text conlatnt various alphabds
I // Outpuls ~ A tree T aging oshich codewords can
be obtaluud fal a characher
step! - Create n trees uhere nm ote dh number df
alphabets such that rach node contains
/ Ihe alphabek 4 Areqpurnest of alphabet ', Arequenaies. “ Make ons of them as di Dedt _
ee rrr
Tey tee eels eae clectoe Ut” Clee le Gn othe weep
Repeat stip 2 util a xing ee as cbbatnd
stepa- To get a codeword tor a alphabet of:
wr oat leaf Level, stark from ea oad at
obtafned . tOhenever we move towards hfe,
vead at 0 and ushenever we move ‘towards wight
wvead os | the string Bets ed ee
code word. _
ts Covulvuek a HofPrron Coda Foy fie fo |lowsin,
data N
Characters | A 8 Com a = |
FPrebabili ty a4 O! 0.2 ots | O15
Encode “ua saxt ABACABAD
Decode ~Lhi lucoded text looololi poo lO1O
stepr- A‘0.4 Bi 0.1 C:0.8 dD: OIg + OS =
step2- Az0.u C0.8 =: 0.15
Bro. D015
étepa 01a 6.38
A:0.U Bio, DOI 1015 Cr0-%
. ome !
” ih tie. * 4Tot eT A eT een eT
2 Construct bata ae der fol losing dels
Lcher | a [a | «|p Te |
Prbabil oO [Link]/o.a | O15]
Encode ta slant ABACABAD
Sted the cl “ext
C1 Ol ooo]
Stept- AtO.4 BLO creas S:5.6 Et gic
Stepa- Add aud
A-O4 Bio,1 [Link] Digg Cr Oza5
shep2- Add 0.95 and 0.4
(6-45 AO. lh le
Biot E:0.15 A
stept- Add ous and 0.65[ee rare nO eee ac ee aceel|
| Coduwsord Ft) | too | Ol eo | tol |
Encoding the skring _
A 8 A c A B A DD
pyr too ti ol Ft toe Wh o
Decoding the abr
oti ng to be decoded | Extract | Chovachr
| Codeuserd
Foeololtioolcy | too B
S OlOlltfootol] | ~o; e
(oT Th [eh 2)45) (70 1] ol c
rrootol) 14 [oA
ooto!| oo pn
lot lol E
|
The = dicooed Rhaing kb BCCADE
Frteaps aud Heap Sort
tleap- A heap is a complede. binary lvee ov an
almost complete binary ~tree satisfy sng Lae,
parental dominance wequirement .
Al heap can be ~ tivo qreepa
Ascending heap (Max leap)
Descending heap (Min heap)
Max heap- tem at any given node 2s grates
than or zqpot te the Legt child ond
wight chad.
CC i iae 15,
Q @o ©
Max. heap Not a heap 2) Min heop
Constructing a heap using bottom-up approacd.
Algorithns bottom -up- Meapify (n, 2)
ogee eee ete
pei
iteme alp]
CH Axpty]
while Cog n-1) do
A (c+icen-t and aCe}< afce+i))
Ce 4 |
evol Y
cf : lane < aCe} )
ACP] = afey
pec
CH axpt]
else
break
enol ty
ate eae ee
eee1. Combbruct wrax haap for the Follousing
eliwanls vaing bottom up approach °
6a, 31,84 ,96 14 yt
Given, 6a
3r Sy
slept. Consider He task nom eof node Sy.
— Compare et with sts children, 84 es ae
Thea ey Cell (ie, be satisfies Ha max hop
and no change fs Fe qpatreel
@) ©) ©
Seep2 - Consider the vixl nontleal node 31.
31 4s less than its Lepe chetd 96 and
greaker than ats wight child , So soap
31 and 46
er
condition
6a
@) @y
C) O®stepa- Comsider the next nm brad node 6a
6a is lesser than +k tefl child 46 and
right child eh. Se susap 62 awd 46
Ge
(Es) (@y)
C) OM @
Heap Sort
used to arrange marmbers te ascendliag x
descending order
Algori ‘thw luap- soxt (n, ac a)°
stepl- (Create tle hap uring bothm -up- opr)
bottom-up -heopt ifu(n, a)
Slaps - [ Pipeoted axcha voot wilk Lost deol
and. wat a hor |
dow -n-1 doum to O
xchange ale} , aly]
bottone —up-heapify ($a)
cad or
relum') Sort the following cdenends sing hioh Sort
62, 31,54 , 9619, Yr
create the dap
Exchange @)
afte} 2(6 | ©) tes)
Exchange (19)
SOO)
Sorld Por
[Cor the given ade nunds
Exchangs (19)
afo} als} uF
KR
Exchange @— v
Exchange KD y
ate} atid ge) &
@ @™@
Sod pom
19,31, 4% ,62,84 98
Sorhd cknuut aremake change (7)
Cc fico, 25 a 10,5, 1
sole { 4%
sume—O
ushile (suns |=)
Xe dargest thin sn
sf one Race stn len
elurn No Solution”
se Sh valu 4%}
suure Sumrt %
ole gach thal sum+xen
velurn S
D) the covn clenominaduons are Le (eee)
obtare th change for an amount: S=0
Given, ce {1,5,10,20,954
mM 2 £0
SuWwWe oO
while (summben) whee (0! =H0)
§
A O +385 640
Sun scum +4 sUm=0+4 35
>
4 whit (as | =4o)
{
a54 10640
Sum 9 5112
(while (35 !=u0)
{
3545