chapter 11 projects
TRANSCRIPT
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 1/16
Chapter 11 Projects
1. [parts a, b, and c after §10.9; part d after §11.13] Game of Spawn !
"r#te a pro$ram that #mp%ements the $ame of Spawn.
1
&t's act(a%%) not a $ame #n the trad#t#ona% sensew#th p%a)ers compet#n$ for a w#n. &t was or#$#na%%) #n*ented as a s#m(%at#on of reprod(ct#on and
$rowth. +ere are the r(%es!
• he $ame #s p%a)ed on a rectan$(%ar $r#d of ce%%s.
• - ce%% can be dead, #nd#cated b) a b%an, or a%#*e, #nd#cated b) an /.
• - dead ce%% comes to %#fe when #t has e2act%) three %#*#n$ ne#$hbors.
• - %#*#n$ ce%% rema#ns a%#*e on%) when s(rro(nded b) two or three %#*#n$ ne#$hbors, otherw#se #t
d#es of %one%#ness or o*ercrowd#n$.
• wo ce%%s are def#ned to be ne#$hbor#n$ #f the) to(ch on a s#de or a corner.
St(d) the fo%%ow#n$ spawn $enerat#ons to mae s(re that )o( (nderstand the r(%es!
$enerat#on 0 $enerat#on 1 $enerat#on $enerat#on 3 $enerat#on 4
a5 Create a c%ass named Spawn that!
• Conta#ns a grid arra) #nstance *ar#ab%e that stores the p%a)#n$ $r#d.
• &n#t#a%#6es the grid to the b%an spaces and 's shown #n the $enerat#on 0 tab%e abo*e.
•
Conta#ns a nextGeneration method that transforms the $r#d (s#n$ the spawn r(%es shownabo*e. Hint ! 7se a temporar) *ar#ab%e to store the ne2t $enerat#on. "hen done creat#n$ the
ne2t $enerat#on, cop) the temporar) *ar#ab%e on top of the grid arra).
• Conta#ns a print method that pr#nts the grid arra).
• Conta#ns a he%per method8s5 #f appropr#ate.
Create a c%ass named SpawnDriver that taes (ser #np(t and prod(ces the fo%%ow#n$ d#sp%a).
Samp%e sess#on 8th#s m#m#cs the f#rst three $enerat#ons shown abo*e5!
--- S P A W N ---
Options: (n)ext generation, (p)rint, (q)uitEnter n, p, or q ! P
""
"""
1 h#s #s an adaptat#on of ohn Conwa):s mathemat#ca% $ame ca%%ed <#fe, as descr#bed b) =art#n Gardner #n
Scientific American, *o%. 3, no.4, >ctober, 19?0, pp 10@13.
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 3/16
""" "
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! p
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! e
Nu'er o. generations to e spawned: 4
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! p
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! n
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uit
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 4/16
Enter n, p, $, e, or q ! p
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! e
Nu'er o. generations to e spawned:100
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! p
Options: (n)ext, (p)rint, ($)oad grid, (e)vo$ve, (q)uitEnter n, p, $, e, or q ! q
2. [after §11.3] -SC&& ab%e !
"r#te a pro$ram that pr#nts the 1D@character -SC&& tab%e. &t sho(%d pr#nt the tab%e #n e#$ht tab@separatedco%(mns. he f#rst co%(mn conta#ns a Eec head#n$ 8for dec#ma% n(mber5 w#th the n(mbers 0 thro($h
31 be%ow #t. he second co%(mn conta#ns the -SC&& characters assoc#ated w#th the n(mbers 0 thro($h 31.
he ne2t co%(mns conta#n the s(bseF(ent n(mbers and assoc#ated -SC&& characters. See the be%ow
samp%e o(tp(t for deta#%s. e aware that that o(tp(t was prod(ced b) a pro$ram r(nn#n$ #n a conso%e
w#ndow #n a "#ndows en*#ronment. &f )o( r(n )o(r pro$ram #n a d#fferent en*#ronment, the f#rst 3
characters and the %ast character w#%% probab%) be d#fferent from what's shown be%ow.
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 5/16
ote that some characters d#sp%a) #n a non@standard manner. Aor e2amp%e, the n(mber ? corresponds to a
be%% so(nd. Ho( can't see a so(nd, b(t )o( can see the *acant spot for ?'s character #n the be%ow tab%e.
he n(mber D corresponds to the bacspace character. Ho( can't see a bacspace, b(t )o( can see how
the n(mber D's row #s sh#fted %eft #n the be%ow tab%e. hat's d(e to the bacspace character bacspac#n$
o*er one of the tab characters.
Samp%e o(tp(t!
De# De# De# De#--- --- --- ---
6 * +7 8 0+ 9 ; < += A 0> a* ? 7 5 ++ 2 0@ = B +> C 00 #7 + +@ D 66 d= F > +0 E 6 e+ H @ I >6 & 6* .
> 0 J > G 6 g@ 76 ( >* K 67 /0 7 ) > L 6= i6 7* M >7 % 6+ 7 >= Q 6> 3* R 77 , >+ 6@ $ 7= - >> T 60 '7 U 7+ 1 >@ N 6 n= V 7> >0 O o+ X 7@ 6 @6 P * p> Y 70 @ Z q
@ [ =6 * @* \ 7 r0 ] = @ S = s*6 ^ =* 7 @7 + t* _ = = @= ` > u** =7 + @+ b @ v* c == > @> W 0 w*7 =+ @ @@ " *6 x*= => 0 @0 f * 4*+ =@ : 06 h ** *> j =0 k 0 l * m*@ +6 0* *7 *0 + 0 *= 6 +* ! 07 *+ + 0= y *> z
3. [after §11.?] C#rc(%ar I(e(e !
&n the rea% wor%d, )o( w#%% often be tased w#th (nderstand#n$ and #mpro*#n$ another person's
#ne%e$ant, hard@to@(nderstand code. h#s project pro*#des pract#ce for that t)pe of wor.
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 6/16
he $#*en pro$ram, shown be%ow, #mp%ements a c#rc(%ar@arra) F(e(e. - queue #s a r#t#sh term for a
%#ne of peop%e wa#t#n$ to be ser*ed. - F(e(e can a%so refer to an) %#ne of #tems where the #tem at the
front of the F(e(e #s ser*ed ne2t, and new #tems are added at the rear of the F(e(e. &nformat#on@
transm#ss#on s)stems, %#e the &nternet, ha*e %ots of F(e(es, where messa$es #n trans#t are temporar#%)
sta%%ed at some #ntermed#ate s)stem node, wa#t#n$ to $et #nto the ne2t a*a#%ab%e t#me s%ot on the ne2t%e$ of the#r jo(rne). - F(e(e's length #s the tota% n(mber of peop%e or #tems c(rrent%) wa#t#n$. "hen
the ne2t #tem #s ser*ed, that shortens the F(e(e b) one. "hen another person arr#*es, that %en$thensthe F(e(e b) one. - F(e(e's capacity #s the ma2#m(m n(mber of #tems that can f#t #n the %#ne at one
t#me. &f a F(e(e #s full , #ts %en$th eF(a%s #ts capac#t), and a%% new arr#*a%s are rejected.
he s#mp%est wa) to #mp%ement a F(e(e #s w#th an arra) and two po#nters, a front pointer , wh#ch
conta#ns the #nde2 of the e%ement at the front of the F(e(e, and a rear pointer , wh#ch conta#ns the
#nde2 of the e%ement that #s one pos#t#on past the rear of the F(e(e. "hen the ser*er ca%%s /ne2t, the
front person $ets ser*#ce, and then the front po#nter #ncrements. Jach new arr#*a% #ncrements the rear
po#nter. -s t#me passes, both po#nters mo*e to h#$her *a%(es. Eoes th#s mean that the arra)'s %en$th
m(st eep #ncreas#n$ fore*erK o. "hene*er e#ther po#nter #ncrements to a *a%(e eF(a% to the arra)'s
%en$th 8thereb) ma#n$ #t one $reater than the arra)'s ma2#m(m #nde25, )o( reass#$n the po#nter to
#nde2 0. h#s effect#*e%) connects the end of the arra) to #ts be$#nn#n$ and maes #t circular .
he fo%%ow#n$ Cir#u$arZueue c%ass #s f(nct#ona%%) correct, b(t #ne%e$ant #n the three p%aces
mared /#ne%e$ant. &n th#s project, )o( are to 8a5 #mpro*e the #ne%e$ant code, and 8b5 #mp%ement a
dr#*er c%ass that f(%%) tests )o(r Cir#u$arZueue c%ass.
&n part a, )o( sho(%d pro*#de a new Cir#u$arZueue c%ass where the or#$#na% Cir#u$arZueue
c%ass's cond#t#ona% operators, embedded ass#$nments, and embedded #ncrement operators are rep%aced
w#th#n the is&u$$, re'ove, and s/owZueue methods. +#nts! Ho( sho(%d rep%ace is&u$$'s code
w#th more compact code. Ho( sho(%d rep%ace re'ove's code and s/owZueue's code w#th %en$th#er,
b(t more (nderstandab%e code.
&n part b, )o( sho(%d pro*#de a comp%ete Cir#u$arZueueDriver c%ass that f(%%) tests the
f(nct#ona%#t) of )o(r Cir#u$arZueue c%ass. Ho(r Cir#u$arZueueDriver c%ass sho(%d!
• &nstant#ate a 3@e%ement C#rc(%arI(e(e.
• 7se a %oop to add str#n$s to the F(e(e (nt#% the add method ret(rns .a$se 8wh#ch #nd#cates a
f(%% F(e(e5.
• Ca%% s/owZueue.
• 7se a %oop to remo*e str#n$s from the F(e(e (nt#% the re'ove method ret(rns nu$$ 8wh#ch
#nd#cates an empt) F(e(e5. -s )o( remo*e each str#n$ from the F(e(e, pr#nt the remo*ed str#n$.
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM Cir#u$arZueue1avaM Dean I Dean
MM /is #$ass i'p$e'ents a queue wit/ a #ir#u$ar arra41MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
pu$i# #$ass Cir#u$arZueuem private Stringl queuek arra4 t/at i'p$e'ents a #ir#u$ar queue private int $engt/ 6k nu'er o. .i$$ed e$e'ents private int #apa#it4k sie o. arra4
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 8/16
end add
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
\e'ove t/e va$ue at t/e .ront o. t/e queue and t/en in#re'ent .ront1
pu$i# String re'ove()
m i. (isE'pt4()) m return nu$$k e$se m $engt/--k return queuel(.ront .ront #apa#it4) 6 #apa#it4- : .ront-k
end re'ove
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
Disp$a4 t/e queueJs #ontents in .ront-to-rear order1 pu$i# void s/owZueue()
m int #urrentk used .or wa$3ing t/roug/ t/e queue
#urrent .rontk i. (<isE'pt4()) m do m S4ste'1out1print$n(queuel#urrent)k w/i$e ((#urrent #urrent #apa#it4) < rear)k end s/owZueue end Cir#u$arZueue #$ass
4. [after §11.?] Po%)nom#a% &nterpo%at#on !
&n th#s project )o( wr#te a pro$ram that #nterpo%ates between data po#nts. &nterpo%at#on #s w#de%) (sed#n emp#r#ca% sc#ences %#e a$ronom), so for o(r data e2amp%e, we ha*e taen some act(a% data on the
$rowth rate of oats, spec#f#ca%%), the dependence of the mass of dr) matter prod(ced on the rate of
fert#%#6at#on w#th phosphate 8P>L5. he fo%%ow#n$ 7=< d#a$ram s($$ests c%asses, *ar#ab%es, and
methods.
Eata from ab%e .B on p. B0 of Russell's Soil Conditions & Plant Growth, 11th ed#t#on, ed#ted b) -%an "#%d, "#%e)
819DD5.
#ne%e$ant
#ne%e$ant
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 9/16
he Lnterpo$atorDriver c%ass has three c%ass *ar#ab%es. ie.t and i\ig/t are the %ower and
(pper #nd#ces of the ran$e of po#nts to be (sed for #nterpo%at#on. Aor %#near #nterpo%at#on, spec#f) two
po#nts, w#th i\ig/t M ie.t N 1; for F(adrat#c #nterpo%at#on, spec#f) three po#nts, w#th i\ig/t M
ie.t N , and so on. )p#ca%%), the ran$e bo(nded b) these #nd#ces #s m(ch sma%%er than the ran$e
represented b) the tota% %en$th of the arra)s, and #t's rare%) worthwh#%e to (se more than abo(t 4
po#nts 8c(b#c #nterpo%at#on5.
&n the 'ain method, #nstant#ate dou$e arra)s for the #ndependent *ar#ab%e!
xArra4 j m616, 616=, 616, 61*6, 616, 61=6, *166
and the dependent *ar#ab%e!4Arra4 j m01@, 01, *>1*, 716, 710, =710, +16
Set iTax eF(a% to xArra41$engt/ - . -s for and #np(t a *a%(e for the #ndependent *ar#ab%e, x.
hen ca%% the c%ass method, i''ediatee.t, wh#ch ret(rns the #nde2 of the data po#nt at or j(st before the #np(t po#nt. hen as for and #np(t a des#red n(mber of #nterpo%at#on po#nts w#th &>
statements that %oo %#e th#s!Enter P*O= g'*: 0.25
ie.t Enter nu'er o. points to use: 4
7s#n$ the #np(t n(mber of #nterpo%at#on po#nts as the ar$(ment, ca%% the c%ass method, set\ange, to
estab%#sh the %ower and (pper #nd#ces of the ran$e of #nterpo%at#on po#nts. hen perform the
#nterpo%at#on and pr#nt the res(%t %#e th#s!Dr4-Tatter Produ#ed 71**6*= g'*
"r#te the i''ediatee.t method to #mp%ement a b#nar) search. h#s sho(%d ass(me that thearra)s ha*e a%read) been sorted so that the *a%(es #n the xArra4 e#ther #ncrease or decrease
monoton#ca%%). 8&t wo(%d be s#%%) to tr) to (se #nterpo%at#on #f the #ndependent *ar#ab%e was not
sortedO5 Start w#th a cond#t#ona% operator e2press#on that sets a oo$ean *ar#ab%e ca%%ed
as#ending based on whether xArra4liTax #s $reater than or %ess than xArra4l6. hen, #n
a %oop, #f xArra4 #s ascend#n$ and the *a%(e of x #s $reater than or eF(a% to the *a%(e at the m#dpo#nt
between ie.t and i\ig/t, %et ie.t j m#dpo#nt #nde2. >therw#se, %et i\ig/t j m#dpo#nt
#nde2. Stop %oop#n$ when i\ig/t - ie.t reaches one.
Interpolator
N&nterpo%ator82-rra) ! do(b%e[],
)-rra) ! do(b%e[], %ow ! #nt, h#$h ! #nt5
N#nterpo%ate82 ! do(b%e5 ! do(b%e
N$etJrrorJst#mate85 ! do(b%e
@2-rr ! do(b%e[]
@)-rr ! do(b%e[]
@correct<eft ! do(b%e[]@correct#$ht ! do(b%e[]
@n ! #nt@d) ! do(b%e
@nearest ! #ntM1
InterpolatorDriver
Nma#n8ar$s ! Str#n$[]5 ! *o#d@#mmed#ate<eft8
2 ! do(b%e, 2-rra) ! do(b%e[]5 ! #nt
@setan$e8n(mber ! #nt5 ! *o#d
@#<eft ! #nt
@##$ht ! #nt
@#=a2 ! #nt
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 10/16
"r#te the set\ange method so that #f x #s %ess than xArra4l6 or $reater than xArra4liTax,
the ran$e #nc%(des no more than the f#rst two or %ast two data po#nts #n the data arra)s. 8J2trapo%at#on
#s dan$ero(s an)wa), and we certa#n%) don't want to (se an)th#n$ fanc#er than %#near e2trapo%at#on #f
we do #tO5 Aor a%% other cases, the n(mber of po#nts on one s#de of x sho(%d be no more than one
$reater than the n(mber of po#nts on the other s#de of x. &n the m#dd%e of the data ran$e, the ie.t
and i\ig/t sho(%d be appro2#mate%) ba%anced aro(nd the po#nt. &t ma) be %ess than the des#red
n(mber #f the po#nt #s near an end of the data ran$e.
efore )o( ha*e 'ain ca%% Lnterpo$ator's interpo$ate method, #nstant#ate an object (s#n$
ie.t and i\ig/t for the $ow and /ig/ parameters #n the constr(ctor. hen (se that object to
ca%% interpo$ator. A#na%%) ca%% errorEsti'ate and pr#nt #t %#e th#s!esti'ated error 'agnitude 61=0*@>7000000000
he #nstance *ar#ab%e n #s the n(mber of #nterpo%at#on po#nts between ie.t and i\ig/t,
#nc%(s#*e, and the fo(r #nstance arra)s sho(%d a%% be that %en$th. he constr(ctor sho(%d cop) #nto
xArr and 4Arr those parts of xArra4 and 4Arra4 that are between ie.t and i\ig/t, and
#n#t#a%#6e #orre#te.t and #orre#t\ig/t w#th the *a%(es #n 4Arr.
&n Lnterpo$ator's interpo$ate method, f#rst (se a %oop to f#nd the po#nt that #s nearest to x,
and set a %oca% *ar#ab%e 4 eF(a% to the *a%(e of 4Arr at that po#nt. hen #mp%ement the fo%%ow#n$
a%$or#thm!3
.or ' to 'n .or i6 to i(n-') '" j xArrli { x \'" j xArrli' { x \' j #orre#te.tli { #orre#t\ig/tli den j '" { \'" i. den 6
print 5Error, repeated point at5 i #orre#te.tli j '" M \' den #orre#t\ig/tli j \'" M \' den i. *Mnearest n-' d4 j #orre#te.tlnearest e$se nearest j nearest - d4 j #orre#t\ig/tlnearest 4 j 4 d4return 4
7se th#s chapter's embedded ass#$nment, cond#t#ona% operator e2press#on, and pref#2 decrementcapab#%#t#es to #mp%ement th#s a%$or#thm as compact%) as poss#b%e.
+a*e the errorEsti'ate method ret(rn the abso%(te *a%(e of d4.
5. [after §11.9] #tw#se >perat#ons !
3 h#s a%$or#thm constr(cts pro$ress#*e%) h#$her@de$ree po%)nom#a% so%(t#ons o(t of a %ar$er n(mber of %ower@de$ree po%)nom#a% so%(t#ons (nt#% #t ends (p w#th one h#$hest@de$ree so%(t#on. he de$ree #s ' and the po#nts i thro($h
i' are the po#nts on wh#ch a part#c(%ar po%)nom#a% #s based.
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 11/16
h#s project #ntrod(ces b#tw#se@man#p(%at#on operators 8I, , , !!, !!!, , and 5, wh#ch are not
d#sc(ssed e%sewhere #n the boo. he b#tw#se@man#p(%at#on operators perform s#m(%taneo(s b#t
man#p(%at#ons and enab%e pro$rams to process %ar$e F(ant#t#es of b#nar) #nformat#on eff#c#ent%). h#s
project #s here beca(se the so%(t#on (ses a cond#t#ona% operator.
he b#nar) I and operators can #mp%ement b#tw#se /and and /or operat#ons on correspond#n$ b#ts#n a pa#r of 3@b#t int operands. h#s b#t@man#p(%at#on capab#%#t) enab%es a*a to eff#c#ent%) process
%ar$e F(ant#t#es of raw b#nar) #nformat#on. "e (se th#s capab#%#t) to encr)pt #nformat#on sent o*er the
&nternet and to process $raph#ca% #ma$es. S(ppose )o( ha*e a 3@b#t pattern of 1's and 0's #n an
#nte$er ca%%ed 'as3. Ho( can (se 'as3 to e#ther set to 1 or reset to 0 an) s(bset of the b#ts #n another
#nte$er ca%%ed data!
• data 'as3k4 dr#*es to 1 a%% b#ts #n data that correspond to 1 b#ts #n 'as3.
• data I 'as3k dr#*es to 0 a%% b#ts #n data that correspond to 0 b#ts #n 'as3.
&n part#c(%ar, )o( can (se a mas ha*#n$ on%) one 1 b#t to see #f that part#c(%ar b#t #s 1 #n data. &f
('as3 I data) < 6, that data b#t #s 1. &f ('as3 I data) 6, that data b#t #s 0.
he sh#ft@%eft operator sh#fts the b#t pattern to the %eft b) a n(mber of b#ts #nd#cated b) the operand
to the r#$ht of the operator, and #t sh#fts 6ero #nto the r#$ht end. Jach %eft sh#ft m(%t#p%#es the n(mer#ca%
*a%(e of the int operand b) . he !! ar#thmet#c sh#ft@r#$ht operator sh#fts the b#t pattern to the r#$ht
b) a n(mber of b#ts #nd#cated b) the operand to the r#$ht of the operator. o preser*e the s#$n, #t sh#fts
#nto the %eft end whate*er was there before. Jach ar#thmet#c@r#$ht sh#ft d#*#des the n(mer#ca% *a%(e of
the int operand b) two. he !!! %o$#ca% sh#ft@r#$ht operator sh#fts the b#t pattern to the r#$ht b) a
n(mber of b#ts #nd#cated b) the operand to the r#$ht of the operator, and #t sh#fts 6ero #nto the %eft end.
he !!! operator #s the %o$#ca% oppos#te of the operator.
a*a a%so #nc%(des a comp%ement operator, . he comp%ement operator s#mp%) re*erses the po%ar#t)
of a%% b#ts #n the fo%%ow#n$ int operand. Jach b#t that #s becomes 6, and each b#t that #s 6 #t
becomes . Aor e2amp%e, #f nu'er #s #n#t#a%%) 6, nu'er #s -, and *#ce *ersa.
a) "r#te a pro$ram that (ses b#tw#se operat#ons to! 815 $enerate and d#sp%a) a%% power@of@two
n(mbers #n the ran$e 1D to -1D, and 85 d#sp%a) an arb#trar) (ser@#np(t #nte$er.
Samp%e Sess#on!
De#i'a$ 2inar4*@ 6666 6666 6666 6666 6666 6666 666 6666+7 6666 6666 6666 6666 6666 6666 666 6666* 6666 6666 6666 6666 6666 6666 666 6666+ 6666 6666 6666 6666 6666 6666 666 6666
@ 6666 6666 6666 6666 6666 6666 6666 6667 6666 6666 6666 6666 6666 6666 6666 666* 6666 6666 6666 6666 6666 6666 6666 666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666 6666-
4 data 'as3k #s the same as data ('as3 data)k and data I 'as3k #s the same asdata ('as3 I data)k
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 13/16
-77 6 666
6. [after §11.11] +eap Sort !
&n Chapter 10, Sect#on 10.D, we descr#bed a s#mp%e sort#n$ method ca%%ed se%ect#on sort. Se%ect#on
Sort #s an #n@p%ace a%$or#thm, s#nce a%% the sort#n$ act#*#t) occ(rs w#th#n the or#$#na% arra), andadd#t#ona% memor) #s not reF(#red. he Se%ect#on Sort a%$or#thm has two nested %oops. he o(ter %oop
ran$es thro($h a%% the e%ements #n the arra), and on a*era$e the #nner %oop ran$es thro($h abo(t ha%f
the e%ements #n the arra). h(s, the t#me to comp%ete a se%ect#on sort #s proport#ona% to the sF(are of
the n(mber e%ements #n the arra). "hen the n(mber of e%ements to be sorted #s *er) %ar$e, %#e 1,000,
or 1,000,000, the sF(ared dependence on %en$th becomes a prob%em.
here are se*era% sort#n$ a%$or#thms whose t#me to comp%et#on #s proport#ona% to arra) %en$th t#mes
the %o$ar#thm of the arra) %en$th. S#nce the %o$81,000,0005 0, these a%$or#thms are man) orders of
ma$n#t(de faster for %ar$e arra)s. >ne of the best o*era%% performers #n th#s faster c%ass of a%$or#thms
#s an a%$or#thm ca%%ed Heap Sort . <#e Se%ect#on Sort, +eap Sort #s an #n@p%ace a%$or#thm. A#rst )o(
arran$e the *a%(es #n )o(r arra) #nto a part#a%%) ordered str(ct(re ca%%ed a heap!
• he f#rst e%ement #n the arra) #s the top of the heap, and #t a%wa)s has the h#$hest *a%(e.• -ss(m#n$ that f#rst e%ement #n the arra) #s at #nde2M1 8)o('%% ha*e to trans%ate that to 0 for a*aO5,
the *a%(e of an) /parent e%ement at #nde2 M i #s a%wa)s h#$her than both of the *a%(es of #ts two
/ch#%d e%ements at #nde2 i and i N 1.
o constr(ct a heap o(t of an arra) of %en$th n, %oop thro($h the 8parent5 e%ements from i M nT down
to i M 1. Aor each of these e%ements, #f #t #s not a%read) %ar$er than the %ar$er of #ts two ch#%dren, swap
#t w#th #ts %ar$er ch#%d, and repeat w#th that ch#%d's two ch#%dren, and so on, (nt#% both ch#%dren are
sma%%er or there are no more ch#%dren. he n(mber of steps reF(#red to do th#s #s appro2#mate%) eF(a%to ha%f the tota% n(mber e%ements t#mes the %o$ of that n(mber.
- n#ce th#n$ abo(t a heap #s that )o( can a%wa)s $et the %ar$est *a%(e #n the arra) #nstant%) b) j(st
$rabb#n$ the *a%(e at the top of the heap. -fter )o( ha*e done th#s, howe*er, )o( are ob%#$ed to
perform a d(t) Q )o( m(st tae some new *a%(e, #nsert #t at the top of the heap and do the compar#son
w#th ch#%dren and $randch#%dren (nt#% that new *a%(e /s#fts down to #ts proper p%ace. h(s, each
e2tract#on of a /h#$hest *a%(e from a heap ob%#$es )o( to create a new heap o(t of what rema#ns.
h#s taes an amo(nt of wor that #s proport#ona% on%) to the %o$ of the n(mber of the e%ements #n the
arra).
-s we tae h#$hest *a%(es off the top of the heap, #t $ets sma%%er and maes room #n the or#$#na% arra)
to $rad(a%%) acc(m(%ate a f(%%) sorted seF(ence. h(s, we $rad(a%%) transform the heap #nto a sorted
arra), as we d#d #n A#$(re 10.11, when we $rad(a%%) transformed an (nsorted arra) #nto a sorted arra).
A#rst, cop) the *a%(e c(rrent%) #n the h#$hest@#nde2 arra) e%ement #nto a temporar) *ar#ab%e. hen
cop) the *a%(e on the top of the heap 8at the %ow@#nde2 end of the arra)5 to the h#$hest@#nde2 arra)
e%ement, thereb) con*ert#n$ that e%ement to the h#$h end of a comp%ete%) sorted seF(ence. hen, p(t
the cop#ed *a%(e on the top of the heap, and perform the ob%#$ator) s#ft@down operat#on to con*ertwhat's %eft #nto a new heap.
epeat, mo*#n$ the top of th#s sma%%er heap to the ne2t po#nt #n the comp%eted seF(ence at the ne2t@
h#$hest arra) #nde2, and so on, (nt#% the heap shr#ns to 6ero %en$th, and the comp%ete%) sorted
seF(ence #nc%(des a%% of the or#$#na% arra) e%ements.
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 14/16
a) "r#te a a*a pro$ram to perform a +eap Sort on an arra) of #nte$ers and $enerate the fo%%ow#n$
o(tp(t.
>(tp(t!
origina$ arra4:76 *+ @* +0 + +> 7 =@ * 0 >*
/eap:0 @* >* +0 *+ +> 7 =@ * + 76
sorted arra4: + * *+ 7 76 =@ +> +0 >* @* 0
+ere #s a s($$ested 7=< d#a$ram!
&n the KeapDriver c%ass, ha*e 'ain #nstant#ate an arra) (s#n$ the #nte$er constants shown #n
the o(tp(t abo*e. S#nce /eapsort #s an #n@p%ace sort#n$ method, the arra4 *ar#ab%e #n the
Keap c%ass #s j(st a reference to the arra) created b) KeapDriver, and Keap's methods w#%% be
a%ter#n$ the e%ements #n KeapDriver's or#$#na% arra).
&n the Keap constr(ctor, #n#t#a%#6e arra4 w#th the parameter *a%(e. &n#t#a%#6e $engt/ w#th
arra41$engt/, parent w#th $engt/*, and unsortedengt/ w#th $engt/. he
unsortedengt/ *ar#ab%e #s eF(a% to the %en$th of the c(rrent heap, and #t #s the #nde2 of the
bottom of the c(rrent%) sorted port#on of the arra).
&n the /eapsort method, ca%% the #reateKeap and sortKeap methods.
&n the #reateKeap method, %oop from the #n#t#a% parent down thro($h parent . &n the
%oop, ca%% si.tDown w#th the *a%(e #n arra4l--parent. he pre@decrement#n$ #n th#s
arra) ar$(ment con*erts from base@1 #nde2#n$ to base@0 #nde2#n$, and #t w#%% e*ent(a%%) term#nate
the %oop.
HeapDriver
Nma#n8ar$s ! Str#n$[]5 ! *o#d
@d#sp%a)8arra) ! #nt[]5 ! *o#d
Heap
N+eap8arra) ! #nt[]5
Nheapsort85 ! *o#d
Ncreate+eap85 ! *o#d
@sort+eap85 ! *o#d
Ns#ftEown8*a%(e ! #nt5
@arra) ! #nt[]
@%en$th ! #nt
@parent ! #nt
@(nsorted<en$th ! #nt
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 15/16
&n the sortKeap method, wh#%e 8--unsortedengt/ ! 6), swap arra4l6 w#th
arra4lunsortedengt/, to p(t the top of the heap at the bottom of the sorted port#on of
the arra), and ca%% si.tDown w#th the new *a%(e #n arra4l6.
&n the si.tDown method, dec%are two %oca% *ar#ab%es!
parent t/is1parentk #/i$d *Mparent k
<oop wh#%e (#/i$d unsortedengt/). &n the %oop, set #/i$d eF(a% to the %ar$er of the
two ch#%dren. hen, #f the parameter *a%(e #s %ess than the %ar$er ch#%d's *a%(e, ass#$n that ch#%d's
arra) *a%(e to the %oca% parent, chan$e the %oca% parent #nde2 to the %oca% ch#%d #nde2, and
#ncrement the %oca% ch#%d #nde2 b) one p%(s the new parent #nde2. >therw#se, term#nate the %oop
w#th a rea3 statement. -fter the %oop, set the %oca% parent's *a%(e eF(a% to the parameter *a%(e.
b) -dd an #nstance method ca%%ed disp$a4ree to the Keap c%ass to d#sp%a) the heap h#erarch),
and (se th#s new method to show how the si.tDown method a%ters the heap str(ct(re.
=od#f) the 'ain method #n KeapDriver so that r#$ht after )o( ca%% KeapDriver's
disp$a4 to d#sp%a) the heap, )o( ca%% Keap's disp$a4ree to d#sp%a) the heap a$a#n #n ah#erarch#ca% format %#e that shown be%ow. h#s h#erarch#ca% d#sp%a) sho(%d p(t e%ement 6ero at
the top, e%ements 1 and #n the row be%ow, e%ements 3, 4, L, and B #n the row be%ow that, and
e%ements ?, D, 9, 10, and 11 #n the bottom row. he two ch#%dren of each parent sho(%d be be%ow
the#r parent and appro2#mate%) eF(a%%) spaced to the %eft and r#$ht of that parent. &n the
disp$a4ree method, (se a .or %oop w#th an empt)@statement bod) to set the n(mber of
%e*e%s #n the heap.
>(tp(t!
origina$ arra4:76 *+ @* +0 + +> 7 =@ * 0 >*
/eap:0 +0 @* =@ *+ >* 7 76 * + +>
/eap as tree: 0 +0 @* =@ *+ >* 776 * + +>
sorted arra4: + * *+ 7 76 =@ +> +0 >* @* 0
ow mod#f) 'ain to e2tract and d#sp%a) the *a%(e at the top of the heap. hen ca%%
si.tDown(70) to #nsert the arb#trar) new *a%(e, 49 at the top of the heap and s#ft #t down to #ts
proper p%ace. Ca%% disp$a4ree a$a#n to show the chan$e, and cont#n(e the process to sort the
new arra).
>(tp(t!
origina$ arra4:
8/16/2019 Chapter 11 Projects
http://slidepdf.com/reader/full/chapter-11-projects 16/16
76 *+ @* +0 + +> 7 =@ * 0 >*
/eap:0 +0 @* =@ *+ >* 7 76 * + +>
/eap as tree:
0 +0 @* =@ *+ >* 776 * + +>
top 0 new va$ue 70
new /eap as tree: @* +0 >* =@ *+ +> 776 * + 70
sorted arra4: + * *+ 7 76 70 =@ +> +0 >* @*