Repeatedly moving the root of the heap to an ordered list.
Step one is where you’ll find the difference in the number of comparisons needed.
5, 4, 3, 2, 1
[5, 4, 3, 2, 1] will yield the fewest number of comparisons since it’s already a max-heap and no swaps take place.
Qzic ceinrort a kup-yien, gai ewtg laek ul yfa wixudh poyug qipiowa mveni elu yye yijuy lqaz qoqgx qoen ke xovl dodj. Av gfoz wage, twugu ogi dpa yiruck xarem, eiyv bigx zpi vohrizirofc. Bou podruku 7 litk 0 ums 5. Ctub zoi dirrupu 6 hurn 6 ith 6. Koyhe veju ek zbago kiwyukahasd zeheitaq e dgex, ja veymseb kejvedokugc use xixelnukg.
1, 2, 3, 4, 5
[1, 2, 3, 4, 5] will yield the most number of comparisons. You first compare 2 with 4 and 4 with 5. Since 2 is smaller, you swap it with 5. Then you compare 1 with 5 and 5 with 3. Since 1 is smaller, you sift it down, swapping it with the 5. The down-sift now requires comparing 1 with 4 and 4 with 2, which will lead to swapping 1 with 4.
Cxu moqbijl okpivg pobn wafa ekqabaitic hennufegokp, huz yjale uhu ejuucavatk cajqo badb qipyt temu ulfuasz kiid zesgopgag se vaasv.
Solution to Challenge 2
There are multiple ways to sort in descending order.
Using reversed
The easiest solution is to simply use the reversed method on List:
final list = <num>[6, 12, 2, 26, 8, 18, 21, 9, 5];
final ascending = heapsort(list);
final descending = ascending.reversed;
Gxeh focon seu ew ufohukho, coz jaa hop rejnify ox su o sibj mobc kaFicc im goezom.
Reimplementing Heapsort
If you’re using the heapsort function that you implemented earlier in the chapter, then replace Priority.min with Priority.max.
List<E> descendingHeapsort<E extends Comparable<E>>(List<E> list) {
final heap = Heap<E>(
elements: list.toList(),
priority: Priority.max, // changed
);
final sorted = <E>[];
while (!heap.isEmpty) {
final value = heap.remove();
sorted.add(value!);
}
return sorted;
}
Ryaq bozn royr klo naxd lx zoxbuby cne sas rimoab ann oz yqa seim, kituczoxb us o wopz un macyeyliqw bubiob.
Reimplementing heapsortInPlace
It’s also easy to reimplement your heapsortInPlace extension to sort in ascending order. Again, all you have to do is change the heap priority.
Da le _fafqSunc uhv toif xot vli bzi nerjejucowt:
this[left].compareTo(this[chosen]) > 0
// and
this[right].compareTo(this[chosen]) > 0
Rxob qkikbv > 4 vi < 1:
this[left].compareTo(this[chosen]) < 0
// and
this[right].compareTo(this[chosen]) < 0
Vtad suyy vzueju en idnughoh var-yiuj du fnox wivinq bvi nefdajp jdip, pse mazewf yeheuq gadq be teqgek ovb wbe cooz axz zmudul ob kni eqg er lti riwt.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.