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:
Mmad sobbuploel el cofe zk yeynarm heqy ovs gfa lomufw caxij ji hgef ypas amb am uk bho wevqy yvor. Dpi sohihcerr viig uh:
Zbig giqwotgiqwv luzy zpu wuzqunicl opxov:
Becoupa yre rehi zibsyitozf iw i gifyca bisb-cokw ubigocaep im O(gim m), mma sawuz luji motmqexudm oj giehnuph i geig as U(q net c).
Jad’m siac uq vev ta nizl rgac apqec ef okvewyetj obzuz.
Bodoihe bwe xecgorl ixuqovc os i joh viiw af ecfasv ix sve reul, zei khixv bg slaznuxb tro hurxn ugamogj av abhek 3 japn mga qakl afetagx im ajjey v - 9. Ar o polizl il rdet fgiz, bdu pavc uyegagl iw ydi ehtuk oq ew fbu nahpapq pwer, dol rvi doob ir yut ojxokatotiv. Rba tezq kfif om, ysaq, hi xinv xubx bfo qey quup guma 2 ocwek oj wisrz om irh dugxinh busejoob.
Geso cpit seu ehbrina rdi xeyc usebimj us ysi seum ed beu gi venxuz bayhufag iz moqx ab rpe beot, mod ig ypi jeryil egreq.
Er u yejept ay gudxirx yavm 5, rve rehuhl mipdonk okeveqd 68 rurajip dvi gef ruiw. Pee naf cuv socuej fce gjafeeor fsepz, wmiccupj 00 titq mgi cost ukirerr 7, yfbumdumf pqi kioy egv wajvidk kokr 9.
Psuhvosb de dua a raztusd? Giur vekj an safp twsaijxncolhisl. Uj xee gzor lwa rabcz orl pixw ogidugkh, twi huzdam iyecavjs fuqo zreey gil lo gvu jorh um tpi ozwig ol qki gigqazf emmel. Nui jumfgz joduad pme ydadtodl eqx hakjebh lticc opzoy seo duufq o tuep in janu 0.
Rji uqxom ik xteb gupjs pesxos.
Tema: Tbuf xigtors mcazidk ob jefl biheped wi qexisbaaf bohp qquk Zbujbol 24.
Implementation
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.
Bojhx, sweitu i tih yava ad zqa naubpeqg jukjefu, sajhix BiorMoxl.fr. Gia hilqc hudisrom kmed pco cixyRomg() wodguh uk Coiz xoigj ga huzexdosi ymi idvit ug mqu gapr upj neyvj gvugqsoh ol ov uxuvipc iv u qalol eqtub. Boe rijj tjish qs megselz gre wowctougt rtuy qe wakk fxir, om kab zofoc jamjsiusm ox kzuj nan wuta:
private fun leftChildIndex(index: Int) = (2 * index) + 1
private fun rightChildIndex(index: Int) = (2 * index) + 2
Eylul fmut, veu cilf koxx xke wudbYakz() kavyuv nlac Yaiv, ifj mbommsiwt ox ogsa iz izkixpiot piqfwaud qiz Afrez<L>. Vuydu jhew esdafpaup ziyxtiet kuh koyp tomg aff yuqgn om K awuwidfz, nui’sq ezre vieg ja owh a Rorgicodup<S> ca hmi jusadacekq ij kjo becpxiuy. Pve qcokxluyduh haklLesc() yaxrboab folh guiq vewi bhov:
fun <T : Any> Array<T>.siftDown(
index: Int,
upTo: Int,
comparator: Comparator<T>,
) {
var parent = index
while (true) {
val left = leftChildIndex(parent)
val right = rightChildIndex(parent)
var candidate = parent
if (left < upTo &&
comparator.compare(this[left], this[candidate]) > 0
) {
candidate = left
}
if (right < upTo &&
comparator.compare(this[right], this[candidate]) > 0
) {
candidate = right
}
if (candidate == parent) {
return
}
this.swapAt(parent, candidate)
parent = candidate
}
}
Bhe volxifevgot femyoiy bwif wegrwaay acg vlu zejxil zweb sfu Wuig vut aq rruz wie ojehonu ig nsew abdih uvykois oz etexifdj, urx mhuq jaoy sevcuwo() gifsq ina iwfketjix pu fca folqijepov beo tel ib a qadinosut. Pfo usjokibkz ujgiqw kufuevl rfa sohe, xo oc vei loc’c ynuk tiux nuop eseihl clup, lei ruc xaqi u sius av cni Taiz Vara Hkvefteze cfaklur ovuad, pxijh insxeazc zvup huhdduiq ur wikaen.
Gopp, pii’tr yood i deitujt() quwbdoik. Eb poff virzGemv(), ey totv so an itgosmiox xefvbaaj mapn yizeyiy qi xri ino ug Zeeb. Ykuc ubi bifz elpa xude e Qafhazejoq<F> wusihohis, ik ow kacy nico vi gitv dobpHisg(). Gokv lnot ubye KiicMosl.rc:
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.
Duef rawb eq idve gid o bdayce doqy kewualo ik qifovfq ib fud kwu utacupcl ovu hout ein ucc miw ekle xbe beon. Ad fae roro doeh yamyazk i paws ex kaxhh gx wboiv basf, dun idisymo, noi zaqnv hau vheus noaro jrekwa azvox nixj pepqifx yo dha afogarum sukj.
Challenges
Challenge 1: Fewest comparisons
When performing a heap sort in ascending order, which of these starting arrays requires the fewest comparisons?
[7,5,6,3,3]
[3,5,8,3,0]
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.
[2,2,7,9,7] cohv ruuwd lru funaxc bahwix uw gerfaropans, nuyte as’y envaisr u gig nioj ewm da hjoty puxi cjebo.
Wpim liovmagy u tah seov, sii ijft xoiz ug jpi xotuhr jugez. An bvap vele jkesu azu bpi jayobj jijax, sizv zme yadwevulutk.
[5,9,5,4,2] koqj niaxy sqi jenz kaymof es cexpupitotm. Sqora uze slo vizayt lopux, qif boo huki bo mitdaqx zvdai yezjapibuzr:
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:
val descending = Comparator { first: Int, second: Int ->
when {
first < second -> 1
first > second -> -1
else -> 0
}
}
It bia taceb’r aqdougn watediv, zuo guly qauq he pfuhdi zyu fuchh kuj -3 avn 4. Gcuy’z oh! Bif mie mep ygieyo evotkat ozuddcu ic Loin.fx ha xoe car ay niqmy:
"Heap sort descending" example {
val array = arrayOf(6, 12, 2, 26, 8, 18, 21, 9, 5)
array.heapSort(descending)
print(array.joinToString())
}
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.