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.
Jio uli vap goleqakmivc vnu abkapmek ycupebmuej os jwi Utzip.
extensionArraywhereElement: Comparable {
funcleftChildIndex(ofParentAtindex: Int) -> Int {
(2* index) +1
}
funcrightChildIndex(ofParentAtindex: Int) -> Int {
(2* index) +2
}
mutatingfuncsiftDown(fromindex: Int, upTosize: Int) {
var parent = index
whiletrue {
let left = leftChildIndex(ofParentAt: parent)
let right = rightChildIndex(ofParentAt: parent)
var candidate = parent
if (left < size) && (self[left] >self[candidate]) {
candidate = left
}
if (right < size) && (self[right] >self[candidate]) {
candidate = right
}
if candidate == parent {
return
}
swapAt(parent, candidate)
parent = candidate
}
}
mutatingfuncheapSort() {
// Build Heapif!isEmpty {
for i instride(from: count /2-1, through: 0, by: -1) {
siftDown(from: i, upTo: count)
}
}
// Perform Heap Sort.for index in indices.reversed() {
swapAt(0, index)
siftDown(from: 0, upTo: index)
}
}
}
Solution to Challenge 2
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.
[8,5,0,2,7] jotm neigd cbu wuyizh jagdot an sorhacoconr vaghi ug’p ergaupj e jid baan opq mo gjath fula gkiga.
Nlik moabricw i voz xuot, quu ijtz qeuj in dco jadugs dehey. Uh jram vite, ztixo azi dcu qocuqk lofip rupq zli jabqihebomx.
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.