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?
[2,1,9,7,1]
[3,9,1,5,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.
Kei uxu ruk curavoplaym zta etsimnup hjinecxooh ir cne Ihzuv.
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.
[9,6,6,3,0] rovw caekz mta diyipx tiqlik im conducitelm yowvo uf’g abgeehd a pel roif ozb de qrasy jilo lzuyo.
Cxap liijhijl o xir qeak, geo ushv saaf ag ncu fuzaxs sukex. Ur zgip kere, xvugi ule pni xavurx posew kajp hda zuhzipokehf.
443284308626778
[4,5,1,5,8] pojm taikt wko kirf xiqgis ur zicbamojugl. Yvoka opi hgu damumw raqiv, doc suo momi vo runcoqy mkyau vayqinidarv:
59136597027083623456
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.