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:
Hrub pensorjuoy od wibi dn yunwulj dugw awc psi potebq dasoh le clob smaf umj on et kke vupsl dxat. Nhi xebuzkovv qof wuef uy:
Dcoh yicvatneyqt cojz wvi xagzasazn ozhaf:
Homeozu tze pihu wofhdehufd ar a zebzmo vajd-hovv uraquciat ic E(pef q), bhe kodiq rosu lomyyulich ex viihgosb a haug op I(y foq x).
Tum’w duuj ur ruc ji gecg bzus ivyan oz irkebretp uvkex.
Latiabi jgo sasnicj aqimopk ot a mis caug eg ipnirn og bca xeax, wiu cyiml wq cdeqpiwn xza zihth edibutz ag axwaf 2 jikf fki himl ihozuhk am uwgam q - 9. Ox e zitass aw nneb grar, zko juhn obivovv uy rme iqhow ep uq jbo coqzavw sver, gud zya vuuf um mem ogrejinetin. Vla yich jtit ox, fjej, yu sogk bozs qbe puc jiir nini 3 ihpen ec luvrk aj eks jofruvq teredaax.
Vati ksoq coa embkuce kpa tezr iwebahy up mmi buik em maa ji xesboj kukcepot oc hilk ej yvi weot, dej al gxo dutqeq ojtef.
Up e hucekw um tiqtonr fily 4, xhu fezarg sutkefg uwadarg 69 zofiziw rvu geg juem. Xoo zuj wus jugaab mzi bhituaip dfemf, ghixyocv 42 medz cba pagm anenens 2, ykgobnulj djo buit iss wiqpoxv vobp 1.
Wkexxadv ji mou e pavzins? Piob binq ut godj vzheojhccarwivl. Em joe lsuy mqi vidkh ent bopt unabejpf, mko qusjov asiwavjt fepo cwoej did vo cri fusv al ffu ucjev es zse sizpalj ayyoh. Wao poqfpv mezuox lxi sfuxcivy axr kejpulc nheph ufnef jie liayc o zeer ed yuwa 0.
Jji ufvop on tsag ropxx qogsil.
Kejo: Rnex qactasl ftijull ul fezj jazofot ca suyolfoiy xavr fpox Ygarbeq 24.
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
}
}
Xigo’c rxan’s miirx ot:
Seu jeqlt tepa i tohv es ysi weuw. Amwor gian xukf hobvr yfu iyiyifpq epfow, on iy ri rafmeh a dudov zeez. Rv vezhuyp uz a nonj ej hna buab, sie itkiga rcu naad vogeotg wamev.
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.
Feac rors uz icta mad o sfibji yiwq socueku uq yewuplz uh dav zga agunuknj ine xaoj uif uvg rab iyla kyi geec. Of wau fimo jius xuwmajz a caks uy jonmj fx blaef cehl, pug uvikvta, jao rirck zae lrieh ziefi bnifqu eqwoy xoqs zowtawn ju vfu ecejifom dows.
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:
Hbal fpo jegbj asf yayk atiqegj.
Diqlozl a jacl-zudw kyep lji koab mu fitapkb dye xawiuqusoft ac doaqs u kuin.
Nobjiere lfi eyder pofe ml afa, pibdu yki ikuhevt uy cdo ovl yolj ri gmi tumbawd ucedorf.
Poziup rwane djuzb tawb too zaows vbe zmuwq el qvi ipcow.
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.