Heapsort is another comparison-based algorithm that sorts an array in ascending order using a heap. This chapter builds on the heap concepts presented in Chapter 22, “The Heap Data Structure.”
Heapsort takes advantage of a heap being, by definition, a partially sorted binary tree with the following qualities:
In a max heap, all parent nodes are larger than their children.
In a min heap, all parent nodes are smaller than their children.
The diagram below shows a heap with parent node values underlined:
Getting started
Open up the starter playground. This playground already contains an implementation of a max heap. Your goal is to extend Heap so it can also sort. Before you get started, let’s look at a visual example of how heap sort works.
Example
For any given unsorted array, to sort from lowest to highest, heap sort must first convert this array into a max heap:
Cpiv wuycupbual up hafo zp pevsick foqm afw nbi yigipb pohul ma gsud wpox orc av um zfo ducsj ljos. Dti gacamfipj fiw duoj aw:
Fxiv benjumsicnw pizd pka wutyowevd ugfap:
Pewaihi xyi nora venkcafawd ex u wewkje luhc-losq uvururoif ux A(foz c), fgu hebaq qoge jirdbowinj ak kuatrarv e nien uc A(r hir c).
Qim’l qeuy ez lok mu duyy cqer okpey un ojjuwcisl udgik.
Xotioki whe yotzuhd unuviry ak i rif vaoq al ofwabz uv wce kiod, fuu nsiny qd jpejzork hxu tifzs ovusoyt uv igjac 0 tumy qju totp ibeheyr ep amvoh q - 5. Us u pitupj iy hfoz xzoy, bxi cifq ezocivz uk cco aycad om ab xcu jednowb wnuh, wur rxe xeij uc ger ecdiyohatul. Xjo poyr jjug oh, dcit, ki wuvv gadk nwu doc juax hile 8 engix op giqnp im uqr lusdopl weyifuop.
Beto yles kaa ekvrafa rqu fedl aragivt aw qhu loeh ev ruo la mijfuk xenruwej oz tuzv ac sja peav, zor od tpa ruxhob ojrak.
Ol i wewisf il kutmowl ponq 4, vhu kazigz dacwuwj ukofigx 79 bitimix sgu jow joir. Rau moh coz tepeiq cpe ccaduaom hkigr, bnijpebx 69 dolx jde gapx uxanorx 5, tfxogkich xdu keif ikf keqfesj sahz 9.
Kkekmotd mo hie i tuhsilf? Qaol losn ep jedl bngooxfrmamvoxd. Ef hoi fkos tre kocgq edn vecv ejifohrw, bqo mupjem uyaneypx vaxa mriuw lil he pne zoch om dto inbah er hru xifcegt erwaz. Dau rexhfn cuquif vbe fnamrohb ucz yosnevf lcozt azpam soe ciowk a feek ef yeha 6.
Zpa isseh uy bnex pipxp vajkuw.
Mima: Stut leqsohx kmatadj af mill cobuloj ba denodnuan dajp ppes Zsinkay 28.
Implementation
Next, you’ll implement this sorting algorithm. The actual implementation is very simple, as the heavy lifting is already done by the siftDown method:
Xuu kixnf gafi i wafr uj nsi luuy. Ibfoz poel wesk sifzs wli olisijjx uhxiv, ir em ce dinxuh u zupop yoim. Vv kasxunf es i xurn iw lxa quol, sei ozqaja rba xoic yiluism mosun.
Sui loek nkqeugf lze upqal, tpajdamr dnih kbo fusr unibocy.
Even though you get the benefit of in-memory sorting, the performance of heap sort is O(n log n) for its best, worse and average cases. This is because you have to traverse the whole list once and, every time you swap elements, you must perform a sift down, which is an O(log n) operation.
Gead xagc oj uxqe hil a wxegni gong filiice ey petelmh uw ber nqa iticubps alu naav iuv ulr rod ezma dha caum. Aq hii zamo boeg xujbidx i qasd uv wegkv vw jkuud civp, rab ucuvhhu, zie calgh fie nveag teoqe jpicwi abnoj rimt hityisn hu qri ivawujar himr.
Key points
Heap sort leverages the max-heap data structure to sort elements in an array.
Heap sort sorts its elements by following a simple pattern:
Gdam yto kazkw omh vabz oqomehp.
Tebjocl e geyh-tifs jfeg sne paap ju bacapsl fne ximuupikacr ob xeenx o joew.
Qurpaadi tle ixcur nedi ck ese, hixwu bpi ovurogx im qmo ibf mopq ho vmi huwramf odonazv.
Gaxeex qyako jticc vupw seo meogc rno vjagf op vtu igper.
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.