Heapsort

Context: FIT1008_MOC · sorts by repeatedly extracting from a Heap · the in-place specialisation of “PQueue-sort” · guaranteed- sibling of Quick Sort/Merge Sort

Quick Revision

  • 🎯 Objective: heapify the array, repeatedly extract-max to the shrinking tail ➔ selection sort with a fast find_max.
  • 📦 Core Components: build heap bottom-up | extract-max × sink each.
  • ⚡ Key Constraint: guaranteed + space (in-place) ➔ but unstable and cache-unfriendly.

📝 Core

1. The Algorithm (Heapify → Extract)

  • Mechanism ➔ treat array as a Heapheapify, then repeatedly extract-max to the shrinking end.
  • Conceptual rootselection sort with an find_max (not an scan).
  • Direction ➔ max-heap sorts ascending (max lands at tail); min-heap ➔ descending.

2. In-Place vs PQueue-Sort

  • PQueue-sort ➔ add all to any Priority Queue (ADT), get_max × ➔ needs extra space.
  • In-place version ➔ reuse the input array; each get_max frees one tail cell (the “hole”) ➔ extra.

3. Total Cost =

  • Buildbottom-up is .
  • Extract sinks cost ➔ total .
  • No best case ➔ even pre-sorted input is not faster.

⚙️ Core Implementation

🔹 In-place heapsort (build + extract via sink)

⚖️ Core Decision Matrix

(Domain A complexity table — Best / Average / Worst Time, Space, Stability.)

AlgorithmBestAverageWorstSpaceStableTrait
HeapsortNoguaranteed and in-place
Quick SortNofaster in practice (cache)
Merge SortYesguaranteed + stable

When It Flips: pick heapsort when the worst-case bound + space matter (real-time); quicksort when average speed wins (its sink's non-local jumps thrash cache); merge sort when stability is required.

📊 Exam Execution Trace

Manual Execution Trace

Extract phase on max-heap [_,9,5,6,1,2] (1-indexed):

Step / StateTrigger OpsizeAfter sink(1)Sorted SuffixReturn Payload
0 (Init)build59 5 6 1 2
1swap 9↔246 5 2 199
2swap 6↔135 1 26 96
3swap 5↔222 15 6 95
4swap 2↔1112 5 6 91 2 5 6 92

Applied Exercise

Problem: Show heapsort’s total cost is and the build never dominates. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: total — the build is dominated by the extraction phase.

🧠 Active Recall