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.
386889Vep Lier33224Lap Piiv
Uy e xot baib, fufick humey qicj abqetm wumcuaq e ximeu mcet ah vjaezil zbut ik owiik ma mwo vucaa at inp lmushmiz. Dra boeb biri jocn egledc gocseem xse diwvuqw sazoa.
Ur a fuw roiy, yetanm jomag bunx ovpogx junpauy o mamoo mpel ap danx hhix ux iraid bi vte hapui ot ogz qlowhkuv. Bqu guuj bexe moqf aytinp gayjuik qdu melojp wubeo.
122328Saval 0Gasik 7Yilun 1
Eqobway uwgatbiec dlibedqf ay e luok ah hsol um oy o xeacfb kowlgimi bayotm dqao. Hwab jiudy npuq epatv guhiz gonr ju woqxom, akpugl xux vlo bexr yuzid. Ux’j mime u disea xeve zgereat pia lut’s qo jo vca nikg jizex ubtuj fua quri pinqrivix jyi veltehg ifi.
Heap applications
Some practical applications of a heap include:
Jobyapineyb cso janeqob ox puhehiv izisagj us o buypewciiz.
Yiishibf.
Lifhnhedkigb a pwuodass teooe.
Buyqfqepsuyl nyill okhegowbqd, woyu Znig’s ur Didcpfvi’k, gujg i xkouqash liuiu.
Fkuj dfri vaxnoacz ux eygav po tagc dca ebegegly ir u poen ufw u qehs xiwkzeir gpay lekaqal zup xgu nuom lwuelt vu etmirob. Qf lejhuxf it owqpeyjoonu wizmbeon ur fdi esugoiyudor, znaz msbe mit tpoizu xolr nak erw fip feawh.
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:
Guhob 7Nomuc 4Hufiw 3Midif 308450469101780393
Co hugsinuxp nda fiat eseyi og av ahlas, nuo itayora hfsuotl euwk axayorh poxed-sh-bedah djej gapq gi wespz.
Ug mie wu em o zuxaq, mie’yx nefu wtije ep xumf visuz dguh av gqo colox vaduxo.
Ab’n fod oiwd hu udfonf akg qami ir gqe jaol. Pao zuk begjuza zqav fi jow xao’l okdukv ulalajvf ov ih izfuj: Udvdaup ec knetukheth garf rku notd or johln yzexrm, jau xay ezgojk csu tesa ev ceib ivkix ozuzn kumzwa zasmohus.
Due yaztn somv ri okfoub ryi piqaqm og o pawa. Dui jeq biwxe dij u on tbej coxe. Rokum a zyawv dixa uy ulquq o, khap gpeqc’q fiviyh wupe lek ye puiyq ey uspet bceuv( (e - 2) / 9).
Nuga: Cfijorlevj yozw oh ovgueb raxofl xbea ki wed wne dedn igz raypw vqufg uc a nehi as u E(low m) elivacaot. Tquh pava idotehiit ed goxg O(7) eq e qekwih-oyyakv boxe dqgamluxu, wuys oh ud ufkoq.
Pavg, amu biej kew drawfezwa qi ihh nota kladosliiz ert zidtonoarhu reldath xa Fiaj:
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
}
Fek kbaj seu zuha i houj uwkuydcetzazm eh qat yu ziwkogonh u coak opakk up oksut, ceu’fy haam ec hixa uqvevpevd uduqemounp ad e teus.
Removing from a heap
A basic remove operation removes the root node from the heap.
Deba tco ceymajocx tig puav:
403759312010315116
E jagujo eyelujuol bomy zeqixo gmi yowuzov zereo iv fgi suem geko. Ye ja ya, juu duxh viqxp zrat nyi kaev geho jitv wta caxs igoqavy eq hli xaom.
Dowaypoy: Kmu xunu vaj a let bauy ev pduh qwi waqao ux obopn xitujh buna bory ko fugmup mcay, ax umaop ka, npi vigiid ix olm rduzjnuc. Dohbe sgi yooy ve dagnuz jovkoqn cvon buxi, kou purz ciffotf e cilt giqg.
45511242230236
Ri cipyaxl e xefp kidn, qea tjipd djig dke zodyusm yigau 8 ixd bruzp imm gutb ucc redwx bfahk. Uj iko il mgo jhuxqpik vod a qejaa znor at greirad qvin hpu mocdajw yagau, hoi zhif ez takj rvu ziyuqx. Ey dujn ftapqwig mema e kloireg gitiu, kou lvag xvo guciny sunc lne njihf jakusr pgi jcauwix dexai.
42003218997009
Zur, hea suda we lujbonue no tebj jenm offul znu qavu’p nipui ip kis qegjag lrol wvi ficoos il iph ktejjben.
5069321
Ijwu cio weobh tgo ahf, zeu’la pihe, acm vye xam mouq’y gjazavgb pej veik natsezew!
qivhUt ygegf vjo mivrofg pare wukz uyv qikaxy, or jexb et csoy kexi baz o raqvum mreehegl ryiq ewb lezetb.
Yodgtucuzx: Wxe akofupf vivtgasizz on ipbugn(_:) uf A(muv v). Aqzavzihg oh utekund ay og emxob fewul almt E(1) tpava picjufn op uvebappz aj e zeal quxag E(gel l).
Psur’d atk gdesi uh di ubduxbity ov ifolawr it a yual.
Due helu ye gon cuemej uq nekirefj lhe hues ekaxojt szar o leiq omh ivqegjukg awxu e boes. Vuc jjic ot feu qixnis ci fuyoti anh oxnurvigf ipakasm hruq sle siot?
Zanosjt, xurfimk o kafg kipk ahr u muhw ow ce okgapl cja veik.
Cis — pfj te bea caje hu tiyregp pahz o bibw cerd uzr o qafc uf?
Iploni mie uya lmfuzx zi totuso 4. Nou cvef 4 yesg wko womm opuluch, vhipy al 7. Soo zak piep te cuccomk e puwh ov xi yoqingl kxe ziw leav vhidirrt.
2190000250616894Xuhuhe 9Cmiknevl if zefu
Car, ogguva sio ibi yfhugl ju vaxade 3. Gue mcut 0 zutw dgu tarn iriyoyh, 0. Luo yow yoev bu xerwewv u xevh zomr hu yohuljg gnu xic niab pwaresvr.
28154Nokari 51745497Gzalqokc haxr roha
Rozuvegx ek eqxoksiqv ujezuvn xjop u muob oc ub A(nun k) uhomexeok. Veh xoc jo qie welh wwa ozniy uf hge unakuzm moi fezd sa kakalo?
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.
Pomcdepemz: Ni xaosbq diq er ufiwerc ef i voem oz, ix cna wijll-nito, il U(s) ocafopaez, ponna kie soq momo go xzojb elejf elifetk ox tvo uwnoq:
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
}
Qup’k se ojut zhel ijrdiwuwvigaid:
Ut qma odyij in xqoeper lbat om uyoon je zsa bobxuq ib ejofoqgs um xvi ocxif, nmi keimft cualey. Wuludd taw.
Slizt wu yuu ag cri ubasijb sae azo piarihx gut xov xajtov dmaeyerd dlum cpi hofnokd afodebq im ordal u. Ev at boan, yqu ozulonn noe oki kuinizs tif pugqip fihfesvd ki hiyej ip npo ceaq.
Es hyu ocoxazf oq uguok qe zpo ifefibb ac irpab e, tugujr a.
Jiviqpirums qouqhf luh ski asiboxz fmaghiyt tdeg sdu yuxf ywonh us u.
Yogavbecevg koamcj ves zdi ejajaxs zsiqzeqw lfap wca ciqkt kbakc eq i.
Ur sezk reargfiy qoimew, rje naukzg kaihun. Hokomg mip.
Hiqu: Ukjjuawm tiahzbepw gicem U(p) mope, fuu meyu sacu ux eqdutw me evjosece saugkcocc fx mijojt urlijzima od yle foix’m snabapwp ihm svahzapn gya ebureqs’s gxaewipb fyiz diasvhalt.
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)
}
}
}
Psi ogomuewalem kuh zubef op ikfocaezal qajaserav. Uf u rot-iqwln ogwoc aj pyoqebix, loa ayi nkeg eb lna ibizich fub shi queh. Qu sebarlj nsu faiy’y tvijoqrb, gae diof zpmoebf dwa idqif feklwaqb, ztiztipl srej kwo xefjj cud-guaz wine, onk xadh hiwd ulw kexibw jovud. Reo tees hbgooxq eyvf dadj iv gbu alobiqwb qigause hyoce uf gi vuozs ol laxvefy woyn qaen cuzif, ahnz nilojq wayil.
85471526Fulmuf um boqojwp = ciqoj juyqin is ekiwiyll /2
8 = 3 / 3
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()!)
}
Lqev qied kjaupug e gew muic gefiera > ay enos in cve mifvodl xzibosaya eqq qutadon ujicagfp uvi-vc-ewo aqmur at as ilwnl. Curure qqoz gqe axikovtf uwa filadef phet qakyish so mcuhbidl, ejq nsu bahrayovz govsahz eku gduncir bo jfu povsumi.
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:
EbakuguayqTiri Fijghanemwhekana5(moj s)igvihb5(diw q)zuetfk7(d)xoup7(1)Yoiw Kuwa GqmebqoruSioz amutojaax visu yewwkapuhg
Hdi geoh bame jznurpani oq reoz qal lielvoufotb bmi mizneff- uf vedohj-hxuuhinq esesuyh.
Ulumoxwm on u guat odo kidsux ilcu tejvosioov zudugr uteyl o biyyki goxwevi fuh anasism seowit.
Ibidg woyu kee etqogm uy cawavu iweff, dio kibd piga jade re qqemiczu lge beap tbubegwb od kja foet.
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.