Overview
| Property | Value |
|---|---|
| Best Case | |
| Worst Case | |
| Avg. Case | |
| Aux. Memory | |
| Stable | No |
| Adaptive | Yes |

void heapsort(int n, int H[static n]) {
build_max_heap(n, H);
while (n > 1) {
swap(A, 0, --n);
max_heapify_down(n, A, 0);
}
}Refer to heaps for implementations of build_max_heap and max_heapify_down.
Loop Invariant
Consider loop invariant given by
A[0:i-1]is a max-heap containing theismallest elements ofA.A[i:n-1]contains then - ilargest elements ofAsorted.
We prove maintains the requisite properties:
- Initialization
A[0:n-1]is a max-heap andA[n:n-1]is empty.
- Maintenance
- On each iteration,
A[0]is swapped withA[i-1].A[0]is originally the largest element of the max-heap and is smaller than the elements ofA[i:n-1]. ThusA[i-1:n-1]is in sorted order. Decrementingi, decrementing the heap size, and invokingMAX_HEAPIFY_DOWNonA[0]fixes the max-heap property ofA[0:i-1].
- On each iteration,
- Termination
- We terminate when
i = 1. SinceA[0:1]is a max-heap, it followsA[0] < A[1]. Furthermore,A[2:n-1]are the largestn - 2elements ofAin sorted order. ThusAis sorted.
- We terminate when
Bibliography
- “Heapsort.” In Wikipedia, April 27, 2024. https://en.wikipedia.org/w/index.php?title=Heapsort&oldid=1220986714.
- Thomas H. Cormen et al., Introduction to Algorithms, Fourth edition (Cambridge, Massachusett: The MIT Press, 2022).