Overview & Concept
Heap Sort is an efficient, comparison-based, in-place sorting algorithm that uses a Binary Max-Heap. It first organizes the array into a max-heap where the largest item is at the root, then repeatedly extracts the root by swapping it with the last element and restoring the heap property via sift-down.
How It Works
Heapify Construction: Converts the array into a Max-Heap in linear O(n) time.
Extract Maximum: Swaps root A[0] with last leaf A[end].
Sift-Down Rebalance: Sifts the new root down to restore the heap property in O(log n) time.
Shrink Heap: Decrements heap size and repeats until the entire array is sorted in ascending order.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n log n) | O(n log n) | O(n log n) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure heapSort(A):
buildMaxHeap(A) from floor(n/2)-1 down to 0
heapify(root):
compare left child with root
compare right child with current largest
if largest != root: swap and heapify child
for i = n - 1 down to 1:
swap(A[0], A[i]) // extract max to end
heapify(0) on heap of size i
return A- Heap Order Invariant: At start of each extraction, A[0..end] satisfies max-heap property: parent ≥ children.
- Suffix Sorted Invariant: Elements A[end+1..n-1] are sorted and strictly greater than all elements in A[0..end].
Advantages & Disadvantages
Key Advantages
- •Guaranteed O(n log n) time complexity in all cases (best, average, worst).
- •In-place sorting: requires strictly O(1) auxiliary space (superior to Merge Sort in space).
- •Zero risk of O(n²) worst-case degradation (unlike Quick Sort).
Trade-offs & Limitations
- •Unstable sort.
- •Poor cache locality compared to Quick Sort because sift-down jumps between distant indices (2i + 1).
Real-World Applications
Introsort Fallback
C++ std::sort switches from Quick Sort to Heap Sort if recursion depth exceeds 2 log n to guarantee O(n log n).
Embedded & Safety-Critical Systems
Avionics and automotive control systems requiring strict O(1) memory and O(n log n) time limits.
Decision Guide: When to Use
Ideal Scenarios
- ✓When guaranteed O(n log n) worst-case time is mandatory AND auxiliary memory must be strictly O(1).
Consider Alternatives When
- ✕When stable sorting is needed.
- ✕When maximizing CPU cache throughput on standard consumer CPUs (Quick Sort is typically 2-3x faster).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.