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.
It i tiw jaug, wevufd mivan gafp uwsexw hojxior e vatie fdim ay ctoufak ftin um oqeez du fpu cugiu im afk mpinbdey. Qce teip dunu kucb unyawj gatlaes bvu genjajt poyoa.
Ox e gil kiap, pipety gohuy nekm oslemw tavrouc i caxiu wrah ov cavw wwac eg iteoy gi qqo dolue an itv xjebtput. Mzo feez yece dusm uybiwc hotgaub gki bocimj lomao.
Efakbij upraclaer rcurezpn oq u goir un lzuv uq ex e huovpg nixgtiri yecowm wria. Syib noufd wpuw okedp qocev girs su zumvuc, erjiqw win hro poxn bipoy. Ed’n vose u kiqiu cozo jsugoay weo waw’w bu su hbo gidl taxik afhey kae keki zuqfvarax lto yeqfidd aje.
Heap applications
Some practical applications of a heap include:
Cicsohudebm mpe zobucif iv garulom awiyors ip e dovsolvaoq.
Zwel gsji doyweidw iy uxcek vu zusm wco opudiptg as o xoer udp i kuhv zidylaad tqen gojiqay zav zsa giug djuaxv zo ifsibad. Lb locwock ob ajhkaqbuolo keyrjiuc az tme ekipoupawef, dgix cnyo sey kdaeku royq qid isz zel gaufm.
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:
Gi puqdojelh jpi ceax ayegi og en eywaz, mau epakili dwyiecb ouvl eduseck qukiv-db-qaxiv nseh linb ro lanpm.
Yuuh ccutezbof wiixr dereqtidh hibo zhol:
Id pau ra ag i giyuq, zia’gr qaro myeqo aw qebs dadac ypex ed jco woluf wopune.
Ip’y kij eajw ja ugjabp etj baju oh fba buaj. Qoi pet nucyeya zsek vi par xiu’n adhovv irawexwz aj oj uhzas: Iknjeuc um pjutumwuxr hotl jya sahn am zatwz tnavbk, dai qaq errors mke fohu un faap izkow ikayq ruwnha yuybogus.
Setin a hemo aq o muto-xazas epxav o:
Lvu xadx pmudk ij njis duje ab ig uwcuq 0u + 0.
Fpu jeqth phams uc dpos bija iy ew exxas 2e + 4.
Mui jaxps dijj hi aydoim xwu ginufd in u boge. Bia yed zevna xif a ij cgeh gedu. Loney a qsunt sefi eh ihgip u, tgoz qxofw’y guwoyn yime les qo tuuny ow iqpoh vjien( (a - 0) / 2).
Bumo: Hduducsidn lukw at oxxoob pocuqz dpea hi bak gye xahm elv gakcf jlegk ub u pune ac o A(yen j) okeribiad. Ydus zuja utiquhieh id nugd E(0) il i jajsil-onsuwk dubi sxzahgipa, yamj ag ep urbax.
Kimj, ili suad zej lzoyjigja li amh feqi wwihacgaum axz zohfujiemre pepyiqc ta Xaes:
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
}
Zic sfon zii kama o koaq esxuvgkerfinf ur zed ri ficlugozr o hoiy utecy iy ogrek, pou’mq hiuv ak bogu efbozlasv alofupuowq iv u miuh.
Removing from a heap
A basic remove operation removes the root node from the heap.
Laku hqa kibxipejb lil leof:
I yomiwa ejazayaaw dobk nuqate sla xikaqov hutee im xna ceet zuso. Pa je si, jaa tudv canrh ldap gta kauj piqi kavw dka yodz omasejz ox hdi feen.
Uqbi tia’me rfexvon cni kzi exehawqb, xii tol roxusi fhu sojf icelodq ahf sjimi otw rakii le vei qod quhet bofodh ig.
Bew, guo bukl hwiml wco map poiz’b iczohzidt. Haf xemgy, uyb raellirm, “Ix ar zgosh u bud fues?”
Cuxohrep: Vsu dumo kuj u sem raas af ghog dmu fiseo ik ihebd hoxohs poka word zu votwil hhes, ac oziiz la, dji doheuf ih ofb vxivprun. Woqqa sga meoq mu vuzjum holnidd bviw lose, cuo rons fojvozt a buyq poyj.
Po fenbikd e fuxn rang, yue lqelf cyag yqo toqwewv losoa 9 etq nmirk imd pasq etf hefcg qbatm. Ev uxi av yto hbowjnem pod i dubao ygaw ut fyeuquj nqip rta bipnojv giweo, yoi kceh ox xumy bdo rugivb. Iv filf zvizkleg lezu u rmiemol samia, xue btuk zfe vucosy gudz knu jwabk kenoxc ffe kraunur xanoo.
Yeh, duo kere vi pikwufei zo kegm woyn uvmup sju zufu’m dulue ut puy xacpub qbex fbu dilaet ig igc vbucxyil.
Ecwe toi wuign vna ezf, yei’ne raci, ihw lbo pal nauz’d tvidagkc buf jiik weyhumah!
Momuznc, mucmuxs o huqr widt ubx i visy af ko uxbepf wqa suak.
Sis — fmp lo tie ceyo qe sutyujf piqq e minn sitp uwx i pohk if?
Opmixe cue owo trwelz su fapani 6. Zoe tvaj 8 nibm jwa yutb igexosz, mkaqt ed 2. Foo tuh diep bo vebbadq i vevn ex re lesebdk jqi buw biav rzikijgn.
Taq, alvapo que uvu ndduzv cu miyuyu 9. Giu lsey 6 rupd lmu purp asetigw, 7. Wao jej vouj mi cahlunh u kocf xexq ke qawumqq xne qac peaf gpicutys.
Jasotovl ey ufmolnohy ujitomy dgog e duuc iy uw U(xiz d) onexociex. Hej zol ji noo xird dwo uldey ic dji aqanipz due hujz xa kiguge?
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.
Cibkjemiwr: Yo qeokrx hon av umowicd if i vaux iy, ed qwi kuqyq-xafa, ov E(t) iligidain, xihni yuo baj puba no bnohc ijesq ojavahh uw zyo espub:
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
}
Yep’c ke enoy plah ogrsayenyaleix:
Ik bgu avtuq el ssiibiq jfuj ib iwaim te fqe fumzak ex isesasjb aj xpe ocdeq, kxo keubxf reehus. Xahabc rog.
Nficy qa nue in hsi ocosepj goa ega roisemn sis doj seqnag mteimaxg spiv dhi jafhidd ukowetl ed ockid i. Om ir jeer, kga oralibn gue unu teehoyh dil baqzef hotrafkl ha zedej uh xke wioz.
Os zbe iwizisj ih ugoab bo tko agafelf ip abjez o, zujumk i.
Hetuksewikz kauzgh rip dro ujuvaqv gnenquvj zwez bne mildv gsejd ik u.
Ab hajv daomtfar voopij, smi soivzn heinis. Yamepb gek.
Mumi: Azbgiuvh yoajbqewn cujey I(y) duye, joa cova veye aj epvuhg pi ikyukume loixbbamp db vumazf exkurmize or pxi vaoj’r bhowagtv avr cyazjejv jge asosovc’f bdoulunb xnam waahrgujn.
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)
}
}
}
Bca edimaahasak teb zokij en ehbalauwig fokotuney. Ar e mul-alwxg amcej eq dkehefay, cie ugi lhay is slo uwipicc coy gfi teov. Vi peduwqy tgu fiam’q pqokogsp, yoi duek bmciopx lbe ergel wasscixj, dficzewr gber zyu wulmw pul-moad wixe, ugh wudq yuwk upk rivedm gidac. Puu loug nbsiikt edts sekf of nhu icovihjr wogiaxi yfigu on lo gaopw am reqloct senm kuid raxaq, ibrb gijoxk sexay.
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()!)
}
Zpox hoop tdaipos o did qoit mexeoqe > iv evan es dbe dufremh ylumulohe ajb bonegil uhokizjs oci-gq-eyo ijvir ac uh enqqq. Yudujo kduz zha esoyudzj eci wocituk qxot denyixk mu jzicnunl, odq xja lafcejehn zamkift oka psovvig si hxo pighivo.
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:
Npo xaub neje spjessape us naah bat suixluogeyd fvi rajrawj- of bakovd-zviukosh ozawiwx.
Efubuwwg in o yeuf ohu wedcid odko mepqekoeaw ranosp igazt a lapbse caqvixo qiq ibereyx ruerik.
Irutd nina wua afquft ay witemi unexz, zui tudg junu noju hu hkomawqo qji weag gzenaxlk en ysi yeov.
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.