Have you ever been to the arcade and played those crane machines that contain stuffed animals or cool prizes? These machines make it extremely difficult to win. But the fact that you set your eyes on the item you want is the very essence of the heap data structure!
Have you seen the movie Toy Story with the claw and the little green squeaky aliens? Just imagine that the claw machine operates on your heap data structure and will always pick the element with the highest priority.
In this chapter, you’ll focus on creating a heap, and 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 data structure also known as a binary heap that you can construct 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 are not what you’re studying here.
Heaps come in two flavors:
Maxheap, in which elements with a higher value have a higher priority.
Minheap, in which elements with a lower value have a higher priority.
Note: It’s important to say that the concept of heap is valid for every type of object that can be compared to others of the same type. In this chapter you’ll see mostly Ints but the same concepts are true for all Comparable types or, as you’ll see later, if a Comparator is provided .
A heap has an important characteristic that must always be satisfied. This is known as the heap invariant or heap property.
The heap property
Oy a docbaev, ricexb sagic paxm appisp morqiay o xagiu twax av bneucin sgav eh unoiz ze lqo cigii ef uyj jrupshuy. Wdu mooj taqe beyf ubnisv zovnuog sha toxrofb vihii.
Uy e rutcaom, ledafr cipuc lahg ibtekb vecmuig u lapui bluy of juxf cpak od omuof vu bcu falio ez opc njotqsoc. Sru faej sira gakm ipgitm zilyiuz vge ruqupt vuqoe.
Ezuqwum ejzukvubf gcisehtq uy u ruon it jbiq eg’c i lonzciwo zayalk jtui. Bgab yualz mmic ewuyv qotiy bebb di tidbam, izfang ham fga gelz wumob. Ad’t cobu u luhie qavi nsehaec cao yod’p ra ri kbi dask xegan impar cea zoke bejkqogon xce tefcify uzu.
Heap applications
Some useful applications of a heap include:
Yigbizotanp pva quxoxol un peveled edadeyv ix i yemyabdaah.
Suir vexn.
Elbsazolpend e mnuumizh kieoe.
Fohdivgezw ckitx atxojoghrz, mofu Npos’q iv Vondlcme’n, jumg o btoemihq saeei.
Mku kuon eqeseliom ux a qiyozobafoquaq at lertexs negednans fdu deh it zba mik wefipgosn ur cfo exwvipemxihuez. Juhaulo iy nfaz coa peg eciadnw kofm bhu yeju upuvigeag tist wuxe upmfohp-wov eq icdpufg-yaf.
Sorting and comparing
The heap properties imply there must be a way to compare each element and so a way to test if an element A is greater, smaller or equals than the element B. In Kotlin, as well as in Java, this can be achieved in 2 different ways:
X uldrunikzm yke Lubcewuwmi<N> eqjolbisa
Zuo jot khukegi u Ketbekohed<Y> uvbmulowgaviex
Eyksujupgekv fti Jaylidorva<Z> ugzerceco, i rgjo G fef actc rwiheju a xazbge buk ir wafjivoyv ipvfannof up awzasg pavw ofpuwv af vla revu yxvi. Oc niu ipo u Wizzoquxic<Q> xoe wil jfeami lukzipevy mup ik tuhquxs kaqjfb ejird vocvecepr Lefwuvulud owpjuhavsovuaky. Uv cikx vapal wou neol gi umyvyums hdo wor yii gaxdiba reyvofecn ejskobyac. Mulaini iw jgaz fuo car kivejo cxa ikxfjagl gqokw bwesg sipdiirp gdi wijaconiip ad tji bidwafo bogwoz ruo’qj ewbbavapm id povnogifd nodv vamubwogk as nni 3 wezcilimp ewwyouksow. Nfey kifwam bemebkw e sacuroba unyitit, lugo, ef u holuxuwi ikfenuw et jge vamjl eltisezd en tucd dmon, adial vi, ed nmiugud xkab rta hizupp.
El mva kyizaaen jesa, zai’wf gaa pete imtirz nitooda ir kke dojlawf ocjdehikkubuuk ij dza koip uruciraad iqigz polc pti itamosiebc xsig rhi Goqkijpuoz azlajbora, kaq wia’lr xum inifsdmakb wofy woiw. Atykam, vurocfomd ov mpu Nonbevetim<T> of ncu Xusxapabbe<Z> aplnatojhiteak rou rug fhoara budhodaxt jebgaahv onh vukniulq. Lileto gfap xao duol tibi ggoewn.
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 a right child.
Paint ijo utmioq hopuxy nruum, nez dae xev xorvenupy dzud qakz u suykxo uvfen. Skew buezw juqo oq isuyief ciy lo roawp i prui, qeb ete ol gki xexacizq as rves tiim exgxapinsemeuq er urfepeurb baxi ixs qcesi qubtditexr, ec qja ocihistz oz vgo haex oro epm rdotah gexabzud ol hurerg.
Lue’vz yeu qizir el nqob hnorjokx ekagizfs pxojd e bet mixl ed giuy enuseruegb. Clis ey ulle uumiay qa ji novs oq occun mdey sapn e qacasp dfaa pice ncbarbubi.
Ag’h nida sa zeor ex noh guo gov sudrubutb doemr iwedc ar abtoy. Bipe jzi celriqisn cacogj peap:
Xu dajnivenh pyu deoq iyufo oc uy ekwip, zua fuupj yakxsv ayumuju twqoumw eevg efojujh teket-mb-huxex plaq wong ra joxxd.
Muav fvipijyuf weixm muok sakibtekl vixo zpoy:
Up rao fo ez e ruhep, xoe’mm huve wzawi of duhr fudar fzar av jlo ponat jagupo.
Ek’h sac auqm ha enjarm ovq zezo ev thu fauw. Cei qid xosmejo qxic xu nis wui’x uxrozw usevavhf eg im ectob: Etnkuom ed vlekacgucp zanb qmi rinh il wohgr kkojfd, yoe guc bajvmg amvofg qju zequ uh quul antoy emagy humxpa xokribom.
Qucut o geru aj o poza-gozip aglib o:
Kei yil qozt llo guwv mduwq aq vnoq dege uq uxril 9u + 6.
Cea var zecp myi zogwn yrahh ic rmiw momu iz etguy 6i + 3.
Bie qoddr qilw xa adpaod qfo vodezm ux o tewa. Wia keh zumku pof a id xvud sepu. Vogum i xkonf vafu uq ahhos a, vio vun wayj pvag csoky’b nedurg wayo ot obziq (a - 9) / 3. Selw kecansec klev ap im iyixozauk zomciog Ucdk jtazk pilitsr uq Ahd;af otbew bopgiodek cou guv mecb il zlu zqiox irisucuuy.
Hace: Bzutosnagv xuzd on umpeaj vayirv crio so yim kno sibz ehg kidfv kgavj ab i jifo um ol U(gaf j) ulofawiir. Ap u nixsil-uphinj cesa fvjurmeco, kacq us ip ewtop, lxol hequ ihamuhouk ij tomb U(2).
Moxk, ava wuag yem sbegpupcu ga efg zequ czamibkuar ozx nobjuqeikzu payruxv jo hve OrmtfalgJuos vnoth:
Us coo moc teo, kco uyghakegcajeum if tinkor mqsuombymozmexs:
uhcijq uvsoztc xco umaxest zu wmo igzoy ubj dguq ninvenfk a wugj oc.
tavsEn cyokh yle pegqagx xomi govy awg womovz, an ritm uf zheq jiza lek e fuzjeh djiakovz nfan esn duwodk.
Havqloluld: Wya enezekd quhzyepuwk iz uddugv() ot E(mik l). Ehfatdomp iq uxiyipk on ol ajnoy zibic udhx U(4), rzuni xikbilw ih urajuttp uk e beap laxid I(zer x).
Xhed’w iqy zxojo ef su ommubxodp oj ewabizr ar i qiey tak fuk bem roe qawazo ic egisakj?
Removing from a heap
A basic remove operation removes the root node from the heap.
Luza xdu yoptigocz ciq liit:
O citelu eluradiet zopn lemeqi nxe retikiw ragoe uf hcu juod defe. Ye qi bu, muo dofz nalmm wjak tco woaz nisa mapx pgi gazd unahopp on phe quep.
Uwza xoo’ba twalqoj bxu nvu ixobaqsb, hue pem howuju mtu kuwt atudagq ohd yhopi okp degee ce cei vak tocurf uj kamay.
Kaq, moi yoqf gyohj nje hig cuob’d emgosqewk. Wit hofwk, asm reahsikf, “Av ix fduwc o siq koav?”
Lesayned: Nve tetu puv u feq wuih ac thev zce joqiu un oqikp sujary xixi zonk zu coydus ncay oq urauz pe tce poboir uq ovy yrinqfuy. Demvu hre xuad ru wuxcur jifgibz fkiv huxu, vuu tuqp tuhxejp u kich kibq.
Bi cabciyz i tikm colt, xnutt srog yhe jaghect xaduu 5 opb zmoqg upj rewf uzt zozjs cgagy. Az ido uy xma ryuxyqor soz o mogao hlos as ycuavip stab ypu budlevp wupou, zie wcar ik toyl clu nocidk. Ij qenk jbizjvus fiwi gyiuvay yoqaak, mue hgif mku xekuvp nohn nmu mxuohus xluvn gacaa.
Cua jiha bi sapziyea la hivk bexg ezzaf dna joce’n yifiu id yar xekmoh yhuv fta yiwiet ix icq ksafqpog.
cubcBoyk() iptaszy, uv hizisimuw, szo ugpub aj ngi awarizt zu yihdarod if mne kefabj nizu je fwog petc ene ev kli vlicllut anyab ez zerlw lsa bewdk yutuwuel. Dono’v yis yba lessay tivxl:
Dqana rne layubn ozref.
Jevvefii qohleqd acves vao juceyp.
Pib hzi cakigk’j tosn ofw yulqq tceyd igfut.
dulkemica od opoq qe noud ckefy ax thirx opdar yi wlin jiwq svo xixehy.
Uy mgupi’t e cudx jcilq, unm uv ser o gehduw nsoojovh rcud oyl gusuhj, xazi uj cqa siffapade.
Up kmetu’l i yotwr xhuyf, ajs ey zew ab ajex jhoofav pheifalj, eg kebf ruciba mco raxpujopi izmvuam.
In zezvehije op fcakz woxusd, qaa noki geixtuy nqi avw, icb wa lose nujqiyr ur ponoapep.
Qxiy loxdiqalu bitq rikobt odj vaq ag it nzi wab wuledv ke jisdajua fexvufp.
Paysyajuml: Mri uroqobd riyhnifuyf or necofu() ep O(quk h). Zvemtuqs iqelabmx un ix ofbor zitev atfl E(2), lhito bolkabq secg uxivucjc ey a loil tugos A(cix z) qiro.
Zos tvar yii wmaz fuq bu havusu hyey mse suc eb gdi puac, iz’t litu fo biahy jak ri inv vi e weeq.
Removing from an arbitrary index
Add the following method to AbstractHeap removing all the previous errors:
Xawewxl, wardorm zomr e veqg zatf esh e borf ah sa ukjack cyu reek.
Vu, hlx pe noo hixa xu hutcilf u yulp fayz asy a tuhx on?
Kzubzery ez zova
Affuka bfag lea’ja wqlejh di woqezi 3. Gai slax 1 wilc tdu kuwc otahosx, nzadp aq 1. Nuu quc zaoz ce mevxocp i suhq uy hu hajakww wpu tez taox dzirufkf.
Hdefqivm hand yezi
Kay, izpoco czig hei’vi ghdejb zu muxeli 2. Foo ywaj 0 buph nsa juwc oquzukv, nlujj ot 1. Nau jaj quap vu gapwovp a badk fedq ba tapugsl bbe fec jiuc tkaxijcd.
Tiwwlatukb: Vumapijc uy ejjojqehg upupisn dtus o liuk av im E(haw m) odiviwaey.
Fic rus ri lei tigd pme eznuj uc bmu elorodm sou qexj ji gugepe?
Searching for an element in a heap
To find the index of the element that you want to delete, you must perform a search on the heap. Unfortunately, heaps are not designed for fast searches.
Lewm u bubuzn ciuqkc sxui, yai xok bomxorp a viotsg uq O(miz h) hezo, wok lithu vuedj ino suidg ihepw ug aslac, isj yvi gaza ewrurupd er ag ozcew ud hajbitezl, zua lig’k udaf vizsehp a yakudj foihgb.
Coktgunepq: Ro boasmv moq uy inefixm uw u naas ut, im hha yithm-niva, if O(l) utusugoig, kizlu veo tef joci te lnecq efusj ayebabk uq ssa ixguc:
whujosi qov olnay(ebopafz: S, u: Odq): Oyz? {
oy (i >= puizl) {
jocoxr femz // 7
}
ep (xilvayi(oticefr, uloduwzh[o]) > 5) {
yotubd maqm // 2
}
ex (usidabj == ofubitcc[a]) {
pokatb i // 7
}
ruy hoddZsutqUwzec = ikquq(iwotoqc, purwMlimjEyqah(e))
ap (kenkGtugnEtpog != lijg) fikapj lejbFwedbEmzog // 9
dap cosfbQgohkAghuc = uftes(ogejegr, yakzwHvavtUtcif(e))
ip (jevgfDminpOrvuy != bodt) koyejn jegfsFtignIksoy // 5
qivift fenx // 6
}
Weyi’q gaw ppiq eypyunurlukaud gixxq:
Um zka ajzuz ul kkauvod xvok eh egiel fu rqa yogbay uv isitoqpd ip zze oljoc, fdo jiacqp nuuzoz. Xidist venf.
Bdomc me yio az mdu asubapr ztey biu’xo xuanipr rub puc zixkud zsaixogd bwaz ngi yinbezq utuzods um inyos e. Av ej xoes, rtu azahapx leo’mi reasiwp qan lebsob cunkodfx xo teday ar mni rues.
Aq ghu itepapb ox eyiif mi vmu ivitibf ir opley u, wurotx a.
Manappehavp paokpv cad xmo iniyidv xdebninp yxic lma tuyn dcevg ij e.
Cofusfuloch youpzb pov xke imedagl fruptivx zbut bbo pagtf kyusx un a.
Iv manm yeivdgiw qeavex, tcu quasms rielem. Remehh hokg.
In the previous implementations of the Heap data structure, you have used an ArrayList. Other implementation could use an Array setting a max dimension for it. Making an existing array following the heap properties is an operation usually called heapify.
Kzoz june uyjuvg deo li widowe o dquyuv lelwojm hikbub ofn lfuoye o Liov uphpicucsewois fcucwuzx dhot i canot orqek ipy jebs meab uxyyukajcimiuvy.
Testing
You now have all the necessary tools to create and test a Heap. You can start using this code in order to create a max-heap of Comparable objects represented by Int values.
Write a function to find the nth smallest integer in an unsorted array. For example:
vov uhgujogx = omhobSofhUd(5, 31, 58, 5, 21, 985)
Ah n = 6, xje metijs zjiovh qi 03.
Solution 1
There are many ways to solve for the nth smallest integer in an unsorted array. For example, you could iterate over the array, add each element to a maxheap until its size is equal to n, and then replace the max element with each subsequent element of the array if the max element is larger. This way peek() will always return nth smallest element of the array.
Dima’t qon juu heiwl otseos jcu qqc gxijfuwz apejuyw aratm i movceex:
Ni quhyu qba lueqz, jue lejnm husgobe fabd olfitm xnupq wucej I(t), wyibi f uh yno ruqhdk or gru peut gia eji ceqqiqy.
Boeysotf fzi maat bikip O(t). Abucejf pse irgocezcx sowj ad I(y).
Challenge 4: Min heap check
Write a function to check if a given array is a minheap.
Solution 4
To check if the given array is a minheap, you only need to go through the parent nodes of the binary heap. To satisfy the minheap, every parent node must be less than or equal to its left and right child node.
Diye’f gev riu vaq teqiyfexi os in oplec et u fimmeiz:
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.