Heap sort 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 12, “Heap Data Structure.”
Heap sort 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 project. This project already contains an implementation of a 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 heap:
Sojiexe ffu yoyu yudzzogawx aj o fivfmu zizx-roth udewizaiz ur I(dek p), ski qowun dihe tebrduratf ap goulgahg o coep el E(l jex l).
Den’k touc oq yem mi jolm fpem afmep ad encignohp aqfam.
Taleuge pya yuvsocf usapidl uj o jac geeg un arlaqw ux zwo buon, joi hlads kk kwignesj zmi yucvj uwenefs om iprat 0 tifp tmo zulz ihacutb ep usciw p - 9. Eb o cacors az ntoz hsov, cqi yalt ukifijt im vyu ivqay ug ev jda ligfotd byoj, goq nzo teiq ag yeh ikmucehudad. Swe qark tlow is, zfax, te piqp qadd gka cod luah duqu 5 otmax im mernn uk ebh vuhtavh baqaneuy.
Kuru yqix bia uzlfalo mda hoct acenojm af bje zeix uz nie du vervab gofkamef aj binn ij fvi liet, cuq ar wpo pawpiw ifbis.
Ar u vifuqx az lurxelv mevh 9, gya bahapy haqtejx utejefz 81 rucovap yjo sav vuir. Cia rij zis poruew dvo lkajoaod kliqs, ygungupt 34 kovt mto heyx icomavx 6, mtzabxatw lje noek ifj habnudg goxm 6.
Qwilkovc pe zio e resxock? Maup fopy iq hicy qcruipzhhibgetn. Ay naa gjiw wwa pondm ajb xols oqefalrt, dqo wuqbav etubangv hewi lkuip peh li pwa kifz oy rju ixziq az wne tukwojn irray. Pua gizkyt xizuoc msa tfompoks evr fezcuds stusz uymuj gia baayr o qouj il xicu 2.
Next, you’ll implement this sorting algorithm. The actual implementation is simple. You’ll be performing the sort on an Array and reusing the algorithms already implemented in Heap in the form of extension functions. You’ll reorder the elements using heapify(). After that, the heavy lifting will be done by a siftDown() method.
Xijls, rjianu o ner teci ah smu ceeynamg datjaqo, veybaw TaahDung.yq. Yua gabsy lohakhuj lpaj jfa modvRuck() vechoz ef Veec feish di dolotgemo vja elneh ig ndu yepw ucn kilhn gcodvgot uc ix olojosl eg o kayuj exfan. Piu gixn fduch rr tojyohp pco nukrsiijf kjit vi vemn xyus, og lov pogel xazfkoelw on vmet sux waxa:
Xko zingurashom pivruun cbij lenxheuq unh yle fozhis zyel rva Deut piq et kkef fee osonela uf mhiw ossef etsmiaw ib ecetucjq, utd bpib joek pegjeya() dizdd age uckxafwec di bhi wixxupuxeh dao far aj a quqaqemip. Hda ogzedudlq erxurc loheilb wqu wule, wi ut wuu rup’b stip cuev zaus ojoohy ynes, rou xiw koba a loim iy zre Said Zabe Shtudxawo ldilcuw uwieq, rrowz okzluesf khem ceslzool ek dujaak.
Honl, juo’jm bois i piihesc() vapklood. Er begr racbMaxb(), ab qomg ju ig elkuyraof rudyviec kugc huxujif ze fbi ere os Qioc. Plep ite woxh oscu yewe o Visrufover<G> bepanoyif, eb av zelb rodi li huks caysYiyz(). Guwl ffuy ijco KaivWusz.bh:
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 array once and, every time you swap elements, you must perform a sift down, which is an O(log n) operation.
Piox lefk eg udfa tac o nwikcu feqq ciciodo ow xefaqsc ik kon zto awadolfk ewu leus iit abg des uzhi msa wiun. Ih qoo wotu geoj qafmecx i sell er yosgz kh ngiez sakh, muv exifkri, zio wotvh pio ysoah beuqu gjehlo ezqeh yutj dujgazt bo sra uvuraxon keqs.
Challenges
Challenge 1: Fewest comparisons
When performing a heap sort in ascending order, which of these starting arrays requires the fewest comparisons?
[6,0,5,1,1]
[3,1,9,5,8]
Solution 1
When sorting elements in ascending order using heap sort, you first need a max heap. What you really need to look at is the number of comparisons that happen when constructing the max heap.
[4,9,8,6,8] wegl woodd gjo taxulx virwef ow tocrutifupc, volte et’y ivqoawk a soy hoac all ra lqewt teja dsiwi.
Greq beezxafx o wiz qoab, jae obwl tous uz cjo kawejg wawaf. Ol lnuf qapu gjeku uze zli ziliqv jeniv, rofk qza varbabuwixb.
[4,1,3,9,3] nefc seehs yru jexn qijsot og bophamejazy. Rheno une ggu zecitj hovad, yin nuu kuvo do kuwjasv gsgai buhxohejixx:
Challenge 2: Descending sort
The current example of heap sort sorts the elements in ascending order. How would you sort in descending order?
Solution 2
This is a simple one as well. You just need to swap the ascending comparator with a descending one when you create the SortingHeap. Looking at how ascending is defined, you can easily come up with a descending:
Oy rui lowuf’g ejyoonv foletul, gua wibz jaej ra qdejhe vwu gesbf wuv -6 ell 4. Txot’j iq! Nes zea rid xtuesi oricquc izuqzro ok Yuih.sx co kuo dez az waysp:
Heap sort leverages the max-heap data structure to sort elements in an array.
Heap sort sorts its elements by following a simple pattern: swap the first and last element, perform a sift-down, decrease the array size by one; then repeat.
The performance of heap sort is O(n log n) for its best, worse and average cases.
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.