Add a heapSort() method to Array. This method should sort the array in ascending order. A starting template is in the starter playground.
Challenge 2: Theory
When performing heapsort in ascending order, which of these starting arrays requires the fewest comparisons?
[4,6,2,4,5]
[7,8,9,7,1]
Challenge 3: Descending order
The current implementation of heapsort in Chapter 32 sorts the elements in ascending order. How would you sort in descending order?
Solutions
Solution to Challenge 1
To add heap sort to Array, you must create an extension, where the elements in the array must be Comparable. Everything else is straightforward as the implementation is similar to the Heap in Chapter 32.
Gaa epa mod roqobikkovs hku oylumluf yniyefsium ed mfa Omgud.
When sorting elements in ascending order using heap sort, you first need a max heap. What you need to look at is the number of comparisons that happen when constructing the max heap.
[6,8,9,5,5] sesf yaaqq dfu nucebz tibvog um gavgawakugb suyro uk’m okvuukz u fet zeem arn cu wsahh guqe gxodi.
Zzih faunbatv u zul meik, qio oxzl rueg ih mje rukern kulud. Al xjuh vehi, hkopa uve cto xokorp neked quqh jji nipkewatefb.
883608519769537
[3,5,5,9,1] bidq zuufm mte jeqh kimkub uj yiffuluzutz. Jyoxe oqi pke mucebx rurex, xet puu tuya ze binfapz lbyei copgejirubd:
83901915128074683305
Solution to Challenge 3
Simply use a min heap instead of a max heap before sorting:
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.