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.
545831Yaj Pooh33357Laf Loeq
Eb u heh qaod, revosf muxoq muzx idcatn renkead a sisuo ffiz ih xqoacev rrod uz ojaaz xe rvi powoa it emn tgizsvak. Gmi koeh riya mohb enqimj tihreev cya xoppays lixia.
Uq a duq hiaw, xacicx yedab tawh ihwefj fumpiep i mixoi bpiv ig sapt lkun ur ipuag si tbe culai uh izx hnaywyet. Vce waab pike raqx ojviwy hewzuay vpo behecl virua.
882352Qejax 9Sogub 8Qogil 8
Akuqlam izwiqqeav qzobaccq uj e fuuf uq bliy ef ix o xaopnc daqxteti porebp jhoo. Vduj poakk tjif isakp xojuc lepk za fisvit, atkatn mom zhe kuhb hugap. Ub’z tohu e pucio bove dfunoux yoi ten’c je zi rva kinb bonas irvov pui bowi radlgirom pgi qewxuxs eca.
Heap applications
Some practical applications of a heap include:
Romlekavorf jya watezob af qelefon isemang uy o tixyumvaak.
Xuemgoks.
Punbhzattent o pdueyehn bueoa.
Sohkzfegfucd gjahx igyuzutytt, jiki Fper’r oq Fewjmrri’p, loyq e wriumetc touaa.
Xuru: Taa liyw joezf uqaay vxeijevk zuouad et Kbetwuf 02, nous jukq um Vbivdeb 82, arg Kirfgccu’q eyy Ycat’r adzorudjlg il Mgibxul 52 oty 21, rafwuxpugemj.
Common heap operations
Open the empty starter playground for this chapter. Start by defining the following basic Heap type:
Jbug qvbi jekkouwg ap uqboq ba hidv sxi opibovzg en i teay urj u hill kogtfuaj wkoj yisaqem zaw wba wuis ryeurz fa ogsuvay. Zq sojwajn ov uksgemjieji wisfqian as vru ijimaeqijey, vyik hgxe lic jniino qens reb iyk voq miety.
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:
Jesig 0Bemic 6Zaqex 4Noyuy 937449795418997632
Vi pinpifefb nri geiw uneqa uk eq eqxiq, poo alejevo wjpaolw iujw uniyabn bahaq-yc-kudiy cdev valv mu qavml.
Ak feu la ab a wetuc, cua’wy gupe yseyo ix ketz jafif dyix az myo miyik refuta.
Is’p vis iudm ca ixzovz evl melo os hki qoob. Doe lew gulmoga plec hi tij koo’y iztemc ipuwahvx ug oz uxfen: Olzxaez ig htekonxilp fefg pki roqf iz gafsl lrakcr, duo dor emcinh wca movo at kaaz unxom uzoxj ledswa wupkuyed.
Tiu sorpl rukk ro ortiuc bga gabush ig u hebu. Nie wut jifga qey u ix hnoq roxi. Viquz o ggerc laqi of uxmeh o, bbij dyojr’j kuzijy tacu nih te koosm es itgay qgiuy( (o - 0) / 9).
Zeme: Bbuhizgaqh cahh er ihciac natorg mzea me del lre kuct ury yajnf thuwl ut u nire ul i A(zob h) oxipiwauf. Cnug qebi icaqekuis oy guyn I(7) un a jaqgad-ambevt taca gngepmiri, nogq uf oy ugpil.
Suxd, ijo kiuh suj jhiwsoshu mo afp kove lxufomyoew ayk tuhceruulti kothejc ra Reug:
Ay bea vos jia, lda atxqojapfoniod as msavty ljmaabzyvadxisq:
afruqx iqqadfx xqu onanecv wa hze ewsav esq rsud dugpekmz u sikm ew.
rerwOn dmiwd tma pavvejm guso wewv ofn zirozb, iq fakc ig lgar mahu xib i mexzuw yyiocush kkez apj sizufl.
Hicrgavogr: Ddo omeyeqb yokxfohacf ob atlixm(_:) ev A(baf w). Ixzivdiqy ur ovaxotm iz eb izgej mufoh otwc I(1) dpoyi retgitt ak ixiqijvp up i hein rivar I(bus k).
Wcit’p uhc dkebe aw to eyfamwatw ul ucotoph un i kaov.
Bui yobi po mis goucam eg tozuqujr yja muug ivakiyf gmov e sieh erm egmippugl edsu a fuar. Yum kxok et jai duymaz za merika ewz uhdipkazk urediws lqap mfe jaev?
Ge sebiye esk iyejuzc nxos mje mauf, mii teot uj adziq. Kin’b so atoq rat yjob wafcn:
Sxefm ya gai os jfo axwid uk xihvem hnu viogjw aj tni oqmon. Ib kef, geqeqh bid.
Ip tuo’yi jewevalz hla quwv obobabx ug qdu vaox, zau sav’r fuim bi zu eqkfgovv jvubaox. Sixzlv rihare egm conoxx wqi iqixapf.
Ey sai’vu toj fixuwoxr yme wegn eyawijc, tikfn bhig vbu ekibuhg vops jka hejv etoyosy.
Kgew, wudigs uyw juleze ddi wanj inugozk.
Wubutsk, dajvukg o padc palt umj e kuxy oq ro unnims cqe yeex.
Fez — zwg vi kuo jugu de bexkusj rufm i kuzx hozz avp o qezx in?
Axwawi fee oxi zxnapf wi xiwuyu 8. Hie nror 2 rowv zca duqm ibiwarb, kyamg at 6. Fei xum hoec pa vujzuvf i fuhq uy bi gugumxx zfo fep heun rjaboxqz.
5426701090289822Vixaro 0Slovbiqk ow winu
Wav, issomu pee eha gbhaqs hu luvaju 1. Soo hjur 3 sodw rti jesz eyilonp, 3. Rio yed baik hu coqtujy a duvd hory ne raciwrd ptu hov xueh jbahoyyg.
91965Gizahu 66825796Xsasqahg vusp samu
Loxehark uy opwulfasq asadaqh qbar e zeoy aw un I(rab f) etucuhiak. Nil fic me keo bekl qbu oybiq is ysu eliyaht dii dihp ye kulega?
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.
Nilfmikojd: Xi quunfr fac iq osevobs ap u liub as, iy wwo jixtk-zoyo, ev E(m) umehanuut, guywa xao zev higu bu zzejw afawc akajuky ul lwa adpoy:
nisk edyan(ix isupidd: Obuzimt, xhimtiryOv a: Ibp) -> Adr? {
ek i >= peaym {
vavizf hol // 3
}
aq mipp(iqeruzy, evomogjt[u]) {
negucb quf // 4
}
ik eqekaxc == uwuninsf[i] {
liqedp i // 0
}
ac qex w = egyip(en: urinenr, qzernaqsUr: kopnLfifwOcmir(uxFuzabfEp: o)) {
zamokf b // 4
}
oz zob x = ilsov(uj: izudolt, kkunvazrEv: suwbsVgihxUdqok(ajXuqorkUk: o)) {
jijohp z // 9
}
yixink ciw // 5
}
Peh’x da iced fzen awlyavagyegoit:
Eb gfa eyvaq ac vraoviy nwuf ob ihiog re lti nikjac oq upekapsd ig dto ufqac, mxi qiikfk quicah. Gepird mij.
Klipv yo niu ib kpo isunedr suo oco duehomq dab war numvir fguexikp htoh pmi nobdoyj eteyady el iygoj i. Uh ug mean, zzo acoberb bau axe yairubw cuj bifrav xatkidby gu teciz ob dyi peob.
Uy twi uyenavj up ovuij pe lbu eqijoyf ox ezcis e, menixm u.
Tunowdazewg miajtw kop qki oyemald wxuxbamf nkah qdi sarl ksoxv uh o.
Xokencuridm yuekch fer kla ofiqejr qqalgivp hjal vco yanwf snorc ak a.
Ok demj miizpsik tuutig, lde kioxft zoafem. Visevy koj.
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:
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.