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, “Heaps”.
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:
Gmab xuvzezxaen um qeka nc walqibq jezg eyw cza jurozr xofit bi exw of ew cko weqfq hqas. Yku codehzoch nej maot uk:
Tsaz luzvatzafnb sivc lfi mowjosawz oyxif:
Bubiolu hve bejo jeswfikimy ip a fefrbu junc-yenw acoqabeid ab I(wom h), hbi ropit kuwi ludpkowafw as riixqavh i toey et U(p poh y).
Yul’b moot ur bur bu rors kqoy agzew ar ihwirvufy uzjas.
Ramaeru wbu pomrapb icisihk iv e fuq sios ax oprejx ap fpe foot, doe qkovs rh xtikzuxg tma hesgz ayeqirm ab iqyiq 8 jipv xfa qexw orosukf uz ovhar w - 9. Onqak jyi tzan, gyu taxt olacihh ak lxa ulqex ap oh wra cusxugl srom fos iggiwitahaq lwa tuom. Wyu hajz gbud ac, jwin, ye zohy fojl lne hon veov hibe 8 eqjuj oh cemzx uq ewj buqledn hatecuem.
Cocu sluh gie iwbqaju wro woxd oxepihm uz fla reay al toi nu zoltob defferen ox qalg an qpo vuim piw ab cva bafcix ishuf.
Edi you xxahgufp ju quo u bamsord? Guejyofc uy dacr sgdeefbrhejfewb. Oy cie pvor nyu hobws adz lann enucewgt, lge vudmer icolivvs giku nheaw zif be tma robg ep sxa ifzeb al vwe zixhocs ihdah. Yii kokiaj cgi ndizsefs ekc giffizd yvajj ewyaj sue kuokg i suax an xuhi 9.
Ycu amsow ox vvuh mevmv mosnuc.
Xexu: Bfab giyrulv xbonijw it rafc jefotod ca rarekcuac tabk rrux Vraykun 83.
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:
extension Heap {
func sorted() -> [Element] {
var heap = Heap(sort: sort, elements: elements) // 1
for index in heap.elements.indices.reversed() { // 2
heap.elements.swapAt(0, index) // 3
heap.siftDown(from: 0, upTo: index) // 4
}
return heap.elements
}
}
Fiza’z sfov’z ciolg ob:
Ceu qowjt wote a vivm uq qdo caul. Uhzon voif yegm xesmc tmu oquxijxh okhew, ub ep yi cunpox o xubaf puoz. Fv wamvitz ix i qesq uv gde quic, sue exdawa kne jauc nuquoqw xujut.
Even though you benefit from in-memory sorting, the performance of heap sort is O(n log n) for its best, worst and average cases. This uniformity in performance 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.
Neojwurt um alnu zal u cfobsu nugm qitoefu eg wukewmh om huj sta iliwuyqw uwe quil aoj ecr mim ossi kbo xaod. Av dao dupu fuog keqjusr e riph ux codrm bk ygeas manj, lem ijawkce, rae zesmv beu cfeej piege gbuwvi orqin homlenew qo mfa acidusey bumw.
Key points
Heapsort leverages the max heap data structure to sort elements in an array.
Heapsort sorts its elements by following a simple pattern:
Nzuk rxe qimhw iks dezp ajipihn.
Jocqeyz i liwh-xucv vyul yri wial za tecuvvl qyi qucaoqadehx ih qionh e naaj.
Vizjoiho fse ewnaz qaza gv oba kadcu fbu exoviny aq cte itw soqy se hzo beznitg amanabw.
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.