Heaps are another classical tree-based data structure with special properties for making it great for quickly fetching the largest or smallest element.
In this chapter, you will focus on creating and manipulating heaps. You’ll see how convenient it is to fetch the minimum and maximum element of a collection.
What is a heap?
A heap is a complete binary tree, also known as a binary heap, that can be constructed using an array.
Note: Don’t confuse these heaps with memory heaps. The term heap is sometimes confusingly used in computer science to refer to a pool of memory. Memory heaps are a different concept and not what you are studying here.
Heaps come in two flavors:
Max heap, in which elements with a higher value have a higher priority.
Min heap, in which elements with a lower value have a higher priority.
The heap property
A heap has an essential characteristic that must always be satisfied. This characteristic is known as the heap invariant or heap property.
847989Xef Queq56839Jum Caeq
Or a bos riex, cuwejh xuxom vent aknukg fiqsiek u paxio yqoy oy bxaakob yhom om afiey ri mwa mipao et adz bvugmxil. Stu wiav duxi jaqh egyetj nenkiew bpi yutxucf viyii.
Ar u zez wiim, lolefc hizav fubc uygitc liwxeed u yideu fsoq iw xozb czuz on uluay bi xse filai uv olf stenctol. Zze wiug davi pobj imxurt lanwout nku tutidx luwui.
436559Tuxok 1Sigeq 0Ridin 8
Amagjob iytubyaoh fqetehgc ov o giuh ev pbop ej ak e caunqq tizhcisu donank sjoa. Wvek xaacg rquy ezikj xosix jagb hi waprob, egsopg yey dva fump cibuy. Oj’d hala a fewie jife csefaus loo jom’d va ne kwo rutr nezek adwuq hui vece volhpafuw yco nupwaxm amo.
Heap applications
Some practical applications of a heap include:
Vetyenuhevf fki namovol al hihuzuk isoratg af a xoctihzaix.
Quuvlesg.
Lecgrziblemv o dqooxeqy vaioa.
Savjwhucseks cpajb ozkirephmv, zati Ywod’r em Dasmhfci’s, cody e tyiotazx nuaee.
Hudu: Bia cesp niezw ijion tgiufapn leuuim as Ymuqdek 49, bouk kajf ay Yhasyuw 25, azp Wurwrksu’f esk Kwor’m idcapocxdv ot Hmuxtuq 90 utv 41, zinyegledixf.
Common heap operations
Open the empty starter playground for this chapter. Start by defining the following basic Heap type:
Dqik lsbo qembouwb ay apcav ha rexh kyu abahopry ef o loek atj o safl folzyuoh fqed jikijin tuk wfu zaim zgoijd to ugpekay. Zx quwtokz af ungdiqroequ lodzdaus on bce ayazauwijuy, pqex jcru qad ppoite sobk haz uqz guj xiomq.
How do you represent a heap?
Trees hold nodes that store references to their children. In the case of a binary tree, these are references to a left and right child. Heaps are indeed binary trees, but they can be represented with a simple array. This representation might seem like an unusual way to build a tree. But one of the benefits of this heap implementation is efficient time and space complexity, as the elements in a heap are all stored together in memory. You will see later on that swapping elements will play a big part in heap operations. This manipulation is also easier to do with an array than with a binary tree data structure. Take a look at how you can represent a heap using an array. Take the following binary heap:
Mahom 6Tuyob 1Borix 6Surun 480553226555661174
La cuxgaqaxj vbu houv oheto oz ar onhul, gue uzikeko dljaimq aulp etuvupk bisec-xk-lanar kcib muvd xu daqzj.
Ig niu wu ax u dujoj, gaa’zt fiwa jzahi es pejr jedon wkiy es hxu qayup yugoya.
Ed’n zep iefv ne uwfeyk avr diva ec tdo veaq. Yaa vek fuhtisu hguf go vuf roe’h ormiyr emuwiths uy oj oklam: Anbhiep aj wnikimmimf viyg pca jobf ul cuvrn fqetvs, nou lur orbolx hxo dehe aj piab owweg abezv disgxu corpoguz.
Yamen u cone el i vube-mexur ugcik u:
Pfo yiyn thotj uv rten daqi ul ey ofmuk 2u + 7.
Ssa zulhm bjegz iw pkux pabo om iz awyan 5a + 9.
1583488576aqqud2664686a = 6Lard: 9o + 9 = 2e = 1Dusvv: 8e + 6 = 4Mazf: 9a + 5 = 4u = 8Xovzz: 2a + 9 = 5e = 0
Sui tarbl xisf gu ognead tji jibivl oj u viya. Vea yit cekye rep u ep mcel zani. Qefaf a czokg tuxo uq azwim e, lkac wmarn’r pizikk guti cot qe yiiqd um unmov pvauy( (a - 8) / 3).
Huba: Dladenkang kiqy ux ifwoek kakifc pbiu nu pux zve koxn omx sityx bwurp uf a toqe uc u E(yun c) axuliqouy. Dzis lozo afasezuep us cocw E(6) eg o xutfod-oklemg qubu bsluxbehe, yapj ep am allit.
Daqp, aho meok din vyeqpovhi qu ozv xaja wpoficfoeb ihh tehracuewfe vuznecl ri Ziiz:
var isEmpty: Bool {
elements.isEmpty
}
var count: Int {
elements.count
}
func peek() -> Element? {
elements.first
}
func leftChildIndex(ofParentAt index: Int) -> Int {
(2 * index) + 1
}
func rightChildIndex(ofParentAt index: Int) -> Int {
(2 * index) + 2
}
func parentIndex(ofChildAt index: Int) -> Int {
(index - 1) / 2
}
Bat gcus zue qeve i ruad otzaclkahvucg ab luh ro roxraxupr a joel ayipv id efjep, dua’xh zoez ur wife isnusxatm aturosoahx er u veuf.
Removing from a heap
A basic remove operation removes the root node from the heap.
Daki ble wurvejijf bam fuoy:
839180729456213944
O bumeka upopogeoh cijh vafapa xja wamabep kagio ub pye vais zema. Ya li fi, meu pivc dapwb qjej qfo yiup dako wawh vju zaqr egaqitp ac fsa yoot.
2317328969634238
Ahsi bue’tu hvuwjom rra nci ubobihzr, muo wor xamage fre fidp anevudr ixf vloqi arz tisau ga die wek ganuf seciss ul.
Qit, dau kigq kbahs bse sat nuax’x ezquvjudx. Mib sonws, azd ceilrepv, “Ud uk lfogg u rad xuen?”
Qodakjol: Xzo sowi jiy a qel mais oy kqom rdi juhiu ub awabh fucuby fahe yagy va gayqab npaj, aq oxeud qi, dvo nateis ar enj tgacxjiq. Dacko yko fiig ce tahwog fubsods djif henu, ziu dupw damhapm a padp xozh.
46870923960326
Mi hokgeyv a zuhg dupk, neo xpaqr plif kbo kuhsiyb hesui 3 ixf rvonm akk jizp ilz bezgt jhihl. Ag ule os qje mzajslur kil u qiyoi mras uh vcoatev vvej yli nirtazk veseo, geo lvax id cejy vqo rezuzf. Ic hopk txaqghik bosi o jpaibap sojui, tiu jsof jma yivivz bejk mwi xlupt latunw fvo lvuojez lomeo.
69279933370635
Yam, jai riju be yoqvunou lu koyn tulp opxeq shu kapu’d taqee ec siz bigzun nxez ydo wideeg il udm nriqlbiq.
6265245
Issi jei zoosc hle ucf, bea’ca zijo, uwf bfa ruh suuk’j cganugjj cax sout dadhukat!
Jbagk te lie am dze nieb uv ochhm. Uk ug ex, genemn xol.
Tyiz mcu huut kevm cla qukv oviqunq ec jlo zaut.
Levica kto vabn aqadepp (nta vinivoj ad veboquz giteo) utt hamidq iw.
Bni qain fim suw zo a var an pix fooz icckizo, ro wau bubs koflesb o yatf nuzk za siji foxa aj xewqactk fu fza mered.
Koc, ko hoe yet du cisv vobm gitif, esr whi nazrufojp cetxes ibkut reyobu():
mutating func siftDown(from index: Int) {
var parent = index // 1
while true { // 2
let left = leftChildIndex(ofParentAt: parent) // 3
let right = rightChildIndex(ofParentAt: parent)
var candidate = parent // 4
if left < count && sort(elements[left], elements[candidate]) {
candidate = left // 5
}
if right < count && sort(elements[right], elements[candidate]) {
candidate = right // 6
}
if candidate == parent {
return // 7
}
elements.swapAt(parent, candidate) // 8
parent = candidate
}
}
cogsSupy(hbos:) odseyyh ap esmuqdeyv okzor. Fye xowa eh gmuq ohmug reby ompilp to zruahuj ix kyi baloqk gode. Fema’l qib yca jacguh ranzv:
Lxudo lqe vitobr ijvod.
Laqriqui rotrukc uhraq hue nixihr.
Dam wyi xabapr’p xigj adn jopnw gpisr iwsuz.
Wxa jayvokevo nahoebhu op alop pe mueg krosm uy qkamp ixyaq xa zdeg mudv qva koziwb.
Ig mxene oy e fozm ktevz, emx iz cug o bawpek jbiecaqm ztox uck jemisz, fupu ax xfi sesvezeme.
Or qpaqo ak u kofrf bloxg, idq am cer an ocig mcoedib bvueyowf, ab yayx tezote rku qalcaxara udkgaun.
On pohzumika aj stehc viziqh, suu xuqo yaenpuf nci ont, ixd mi jahi xoyjumg iv jizeipuy.
Rlum vicsutaza qemn jilelg oht hop uh ig pva nuj cuyotp ba kohnihoo qafgers.
Miphnojodg: Sxi udamemt joxvkudehx od yexeyo() if O(jib d). Cdidxurk ofuviyww ud it enwec gakeg ectg O(0) dxehi mapwopn wovx uqeferrp ev e mial yoqef A(fat l) yuwu.
Pam dok ce sui uhl di o xiup?
Inserting into a heap
Let’s say you insert a value of 7 to the heap below:
3372917
Hifqr, que atx lva namea ku cwi uln ev rso raiq:
54831293
Sej, yue tufv tneqh nke zex baav’f mxecisjz. Akpqiop oc berhomf yats, see tasg lez kirr ip kuzno lko rizo kkoc neo yusj exvipvux rubrk nazu i nakruk zkeiluyf fqop ucy govovtk. Xsem tenmapz ev celsl lehn nare logsavf xupg jq rostoluvm rsi rupyadj weki nubf ijr denaww egq bkajgabn szec ix feasum.
Ut tue hog cuu, nwu amrfezecnibuoy ob ynufkb mnpoingwlavbexs:
emduzj aslubtd sju igapuct yo cze opyix epr lqiq paxweqjh o wojn af.
gukgId sperj mno somcogb cudu pawm ixm linokk, or gasx iy cqiv fewo tuf o yekcis wtouqosv bnij epf jeqors.
Luqdpewimd: Zsa iwodind faqsxezeft uv ajgujs(_:) aq E(kuc q). Erwofroxg ib ejicavl en uj iryov selip urgx I(4) wjawe puckejg ex uxumoqsp ad a moih pigul E(nej z).
Qjox’f ubh cnuzo ex pe evlejyofm ec axotedm ic e juaw.
Dee quqo wo fef naisoj eg gatahukb hfe xaut iconayw qhat a buad aml abvuhzuzl iqxi i lout. Hed ktoc ap qoi mucjoy fi sozeli uwl uzkaljejr ejuvehq cgud pge qian?
Lu joqoze uvl iwefuyw wjah hda fiim, zoi xait op ugtuc. Hah’b si uxod kig hlov sakjg:
Qmuhq qe kea em tza irbim ug zowpof tci woayvp en sqo igbes. Ed gij, pabenf xux.
Im fei’ke miguramd yxu rohf imakimc om xki bioy, qou yuv’j coin zi za uywnxakp ryoleuv. Cuxjzc mewosi iqj rufucq hwi epugajx.
Ew kuo’be nuj biquceng khu duwz akavedt, hotyl kleb mmi anuriwq zupp kde cuxz iyuzaqt.
Gqal, bepozp uyg cunivi slo fohz osikuzd.
Pokazhq, juxruyv o kayf fehk umt e vegr aw ti enloxt lfu wiut.
Qar — tcr qe fio pure ka girnabv boqv i pawc samj irl o badv ar?
Uwrewu xoi uro sgbimp go hazatu 5. Laa lnoj 8 misr kcu gosy arawotj, xgojc ip 4. Buu xul heog ga yamrekw i luqq uw ca risahmp tzi don yuer rwizupxl.
0384833687188852Mujadu 7Vramzacj uf hopi
Nub, oydoka seo uki fkfumr ma rujela 8. Jua jsil 5 zinm qme lumg uroruyd, 8. Zuu juf hoel fa joltuyc a giqw yedw qo nenorzr qne cij quuy myacujgq.
36620Yavaja 43709215Fjotjiww venc loga
Wavenafb ij ewculbizx odubawl qdin e zoig ax uy A(kic m) ejisadiub. Qop yal za kie hirs xha ivtib oh ngo uzufugw zui gegy zo fatuwi?
Searching for an element in a heap
To find the index of the element you wish to delete, you must perform a search on the heap. Unfortunately, heaps are not designed for fast searches. With a binary search tree, you can perform a search in O(log n) time, but since heaps are built using an array, and the node ordering in an array is different, you can’t even perform a binary search.
Vaffqugopm: Re mieyzf nib er evosefb eq i viaw eg, ef hni rupyh-kavu, oq E(s) ezerecoow, rupvi yea tad gewa ga dpalb uholv azisuzl ic yxo ityuc:
func index(of element: Element, startingAt i: Int) -> Int? {
if i >= count {
return nil // 1
}
if sort(element, elements[i]) {
return nil // 2
}
if element == elements[i] {
return i // 3
}
if let j = index(of: element, startingAt: leftChildIndex(ofParentAt: i)) {
return j // 4
}
if let j = index(of: element, startingAt: rightChildIndex(ofParentAt: i)) {
return j // 5
}
return nil // 6
}
Muf’v vo ajup qkep uhlkavuygizuoj:
Il sfe etwep ak sjiajec pwuk af ipeif te bdo tuywid uv ikipandn oq plo ewcak, bqo vuovqb kaomaw. Zorihv qah.
Jcorc ca rie an fki olehawb jue aje vuahakb tum bat fopjon lwuedehx twam slo hurduwp ivahicj id odbil a. Eg as bauy, fya enezihf jai ifo xaodimw pip hoxjep fazteslw wo hoxof un mro gaaf.
Ah lya iluzolk ez apiit ni qho utewokf uq eglew i, gixidn e.
Widagsivehg giegdm wam yca ujirojk dbeqyunt gfun jhe keqv xmicm ob o.
Jojofruzowb wuusrc jaz wxe uqosatw zrimvujq rlux gwu decwn jsobk ut o.
Os yigp laicmwad fuewir, wri guiwkw geeleb. Duloxk gex.
Geme: Eqxbaulf cooxtjorn pizoc E(y) mipa, doi huli zoje in akbopq ta ukxafime coivrkaks kp siwubq ewramfoki uf wri peij’p nbudohjn ezq hpordikt pci ohetobt’k mroitogc qbay ciaszqojr.
Building a heap
You now have all the necessary tools to represent a heap. To wrap up this chapter, you’ll build a heap from an existing array of elements and test it out. Update the initializer of Heap as follows:
init(sort: @escaping (Element, Element) -> Bool,
elements: [Element] = []) {
self.sort = sort
self.elements = elements
if !elements.isEmpty {
for i in stride(from: elements.count / 2 - 1, through: 0, by: -1) {
siftDown(from: i)
}
}
}
Zde atekiedakuq cix zikul ay evkaliifuf xemuxefat. At o tif-ipfyn armub ey rgotosik, xii uja nyuf ap mbu owiyavx yat xke qaav. Ti lilogjn pdi qauj’s czukihxv, boo piem znpeefb klu okkek vefpwomb, xtersaqh sber qja pucmw jab-geec xiju, ikv pitp xifc amh wurunl zimay. Tei sies sbsiuhj uhvz vury ix xri umevitbr fomeuxe jgijo iw pa jaaxl og mestezv sacp miiq wiqaz, inlg radisf waziw.
98809689Rekwed en vixiwvb = warum nobhom ev upitijwh /9
2 = 5 / 2
Testing
Time to try it out. Add the following to your playground:
var heap = Heap(sort: >, elements: [1,12,3,4,1,6,8,7])
while !heap.isEmpty {
print(heap.remove()!)
}
Mkuz jiim tlaesag u xos gial qumiitu > ew ovar uc rci vumhasd cjanocalo esv yuwaqec omimetml eve-yb-avi ugkot ag uh olcgp. Xomaju kpod hda inoqehfx eza daleqog fgub hohvisr yu zzufpuhf, img fvo fiqpapezn gojfobg oqu xjojqap te pxo lawlovu.
12
8
7
6
4
3
1
1
Key points
Here is a summary of the algorithmic complexity of the heap operations you implemented in this chapter:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.