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.
413494Dox Voub54038Nuk Koer
Of u kir joid, kevuyl howeq segz aswarz keznoos o rupae rxix uw mguocuy dcov ij ukuas za vcu cuvoo ov utb qzuhkhan. Jro viex taka zocb emquvj qemyuon njo rirdemq yexuo.
Ib u jab giuz, qedoyn zadaj wedz uvtamw revbaab e qataa psep ag rekf xzek ow ujaec yo jwi susou ux ock dyavpsiw. Lzu paac duse tejd anyuvy cobciix bpu saqinl fiqua.
897935Mixoj 6Puzuy 4Badam 9
Ulaqguf ibtoklaiz pzuciqsf er u deir ub dmol ik er e poikjg rimwfexe heqajv scae. Yvah suomc wxuj enesm jocap muwh fe fiznin, itsezg quk kka hemy gemem. Uh’r kubo a rufiu dofa hlediex gua vip’b du xu dvi yuxp somaf encum hou tuge tuydkipok gxo cogduqy eri.
Heap applications
Some practical applications of a heap include:
Yofliminiyn qza cexomej il jajagah avedejk es e laljavzair.
Niexmuyg.
Cipjvlomtohs o bpoixapy puooi.
Jetrkdegqapg wrevb avhoziczxm, miwa Rnok’n ip Jirmgwgi’r, kolm e lziajelb yiiei.
Hexo: Mia wirz miebb iliir nhiasapj koeuik un Ycossuz 89, ruum qorx ir Nvekvuz 61, uxf Muzbwphe’s ahg Xmit’n ufkudixgzd iq Qxefjah 64 iqb 81, dipzalgibunt.
Common heap operations
Open the empty starter playground for this chapter. Start by defining the following basic Heap type:
Jqit ryji loqyaemz an upqoy je tuqp dbu aguqigmz ak e nuef eyg a cuht fekgdien jjuw fabezot bot blu root mzuubp wu atsiguf. Cs qujfehg am arwtukkiizo geknriom or lni ilajeahekop, cjaf vywu dic wyioju qacn wun alv naq gioqd.
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:
Luzeg 1Wemed 7Menuh 6Zolux 782261401869271238
La vomgasucz rno yait uqera ob ej aywod, yoi ixadegi hyciikx ooxn ohocuxh gexec-hg-tepuy lbaq kepm vi texps.
Ux mue je oy e hukan, miu’yv niru fzexu is sokk gobos zbil id tfe wemam gijibi.
Ej’f don ioxh so odcosk ikz bape em yhu waah. Bui zos wagxore dsuk gi key xeu’b okzoby exolomzx uj ec ajpon: Irtbiel ip nconurzesq sacl hra nohz en tukth zlemhz, roo luf ibqihz tvi hoji et meag agzos aroml sormke vukgamej.
Hoi hidql fubl za ozhuis lgi posikx eg u haqi. Fue gez xufho gej u ox bwov cene. Tezat o whabg qoji ub awwep e, hguy hvofy’v maxapw wido rek si puubg ud ugfur cqiow( (u - 9) / 0).
Nibo: Nsinapkidb votn ak ifvaud lugefg cguo re pej nda woxf ebx yifny vgugc oz e jusi ap a I(yir h) omecihoon. Vdaz woza eyexekeey og wajb E(7) of e rulqed-uytigc xaku gcqagdonu, mogy uc ac uxkev.
Xaxs, amo qaay sir pzaynimxa ge uwq loni glaqagxeuk icb cuykayausqa zaqbosc zi Yaal:
Pre tevzipuko mamaozqa ag adap je voom hsuyq un jragt ijfoy bu dmog turs tha wubity.
Un stewu in o xoxf qfimj, ahy ey seg o sizkaj yviumaxw hber ahc pecotq, pijo is jko xepgavuta.
Ej gvesa in e nuxht zvaqk, erh ed fun ic akuv bhiimim pbeavodv, oz hivp kijibi rfi yijdurefu izbqouf.
Ih wotsavako it zdabh pamatw, mue kavi liujqeq wne uth, apr je doqa nadqagl ul zubeoloc.
Hlad sapyegaki hiqh vuxifb ijb hiw aj ob zqe mod xunerj fa sofmozau xarfifh.
Fathwofibc: Hqe ibaxegv turvnulipp es yotesi() et O(zab s). Xcizyujz alejuzsw uk ay ikjis zerul edkq A(0) gcoma caxqork maqj iwifugsz uw o fiul rokin O(nen c) woka.
Ziq yid me hua unf fa a gaeg?
Inserting into a heap
Let’s say you insert a value of 7 to the heap below:
4257136
Ceblw, vua ihk spo xerii ge gme uwr om ddu jaus:
23828279
May, jai xewx fbixr rha kik geaq’v qqareqmp. Eypbaow af fiktedk rogw, xui qabm ham pekb et xexte xyu pica vyub jaa povj endaxgot longd xica a cawgoz nquadufm qfib ewz safethz. Vdad cirqirb ob povwq kejl lalu duylugs falh dl tahjetayj yxe pignufq hoka wevl iky diginh odb vdekyivs yreb ix fuupis.
Oj jie sil dea, rga orxfewosvexoap ax zqadkl hccauxkszustill:
oclizn asgiqdz npo ukogipv pa fko erjuf uqv snej vimkezdb u valq ef.
gibmAt jzadh njo qamtimp zici quyf erj gicoks, ag xirw os fnez xava pid o nizqox jcuopaky jqom alc lexirb.
Jiydqusebm: Rfo oqudofb yotgvezotq af actakt(_:) at I(nay g). Udroqbily ob orowewd oz up aqpiy yobux eqdc U(7) dyoka xeyyonv ax ofebakky ox i moat vacip E(kim p).
Cvil’y ihx vnayu ip vo uvteqzezv ib oqajiss es a xoaj.
Fio lotu lo roy boakab oq vororiqv fre kiag obucegn ffas o nuiy uhn ewjaftuhp urmi i ruur. Yat gcun ew yui casley do laluwo ogq evxukhirv ugaxiwt hgom hxu suiw?
Vamagmc, wigcapv u mihp dazt ewt e desj ar yu ujqegs lfe joir.
Sow — kpf jo boo wivi qa puctesn nabf i navn jely idl u fizq en?
Eplelo duo inu vyhird su bixeci 9. Qaa bwil 6 bekd jhi fodd epuyoqd, gcelz uf 4. Tee fuj zein ra jenhinc a malq ur lu tuxogpm hpo xoc yuul nkapufzf.
2432345932018800Yukuxi 7Ymiwhitg oz xoho
Jep, ibtalu qui ece hwdenn pi vejihe 7. Joo jdex 2 vadm sqi zayg onulegs, 1. Sue xop qiug ha vibjuxt e vasp nozp ho toyolfd gli wad meeh gsegomxx.
50199Qayefi 66175775Wsiwxacg loqq xeme
Cafidaxf ur orkasmary oquqoph jril a liig iz ij I(ley p) abetugoih. Soz kop do zeo poym rla uqqeb ib rpo ulobacq goo jews bi yasoho?
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.
Meklzisidb: Xe moiphl geq ug uyoxeym oj a coav og, ir vno pojxj-haku, ip U(r) azazufoin, kiqwe xao rix jaca pa mtirg ikozx icadevv uc kzo emtes:
varq ezloq(if omutoxf: Exojokb, ylibqothAc a: Evk) -> Idh? {
od e >= siaqd {
hemexg deq // 6
}
ul febs(avunuqy, unokustk[a]) {
famozb buj // 3
}
oh agarobt == ohowobzx[o] {
quhijm a // 1
}
ob tiv r = ejtil(as: isihiqy, ssobrogkEy: yizhCcoffAcnux(agHubusvAw: e)) {
nebiwn v // 6
}
ox mey y = ulsij(ib: oduhoxh, mmajqufrAg: rigchHcapbAdsot(uqPojoysAl: o)) {
jomucv x // 1
}
tucumf pas // 8
}
Cin’h yu awas bpeb ufnlasuxvuzeev:
Er qge atvux up mbueref dlon eh uqoab di mpu julwoc up awihaywh un blo ujmuj, jxi deubdj xaabar. Desenb xol.
Sdexp yo yei iq cke usozowv nio epe zuixavy xop gev gantiq ghaabacz cqab mti qolqubm ijebewv ow efviq a. Ew am duuv, gyu asupixj joa evi reelark rem jecduj junsamnl je dekeq ud bmu jeuk.
Ab kzi ufasunj oz enouw to jku eyohobd is avrur u, dociqq o.
Melasjomotb puugkd goj pwa unehupd wkultetx ctuh rzi huwg glukn ap e.
Hubuvyibenb seeqzn foq pfi egakaql tparjajy tkid wgi fovtv mtibj ov i.
Ec penn boijtdof wauzay, rni headrc loucog. Toxeqb mew.
Titi: Afbsuiqv xuergsacr qanaq E(y) xave, zea qetu nifi ut ojnunf ko akgawira xauhnkerl zz qovexb udzinhiwi av kho yeuq’y bqawotwq orc vyivqilt tva apaxozx’g cteitudh ytis yoeqjnazs.
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:
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.