Overview
Property | Value |
---|---|
Best Case | |
Worst Case | |
Avg. Case | |
Aux. Memory | |
Stable | No |
Adaptive | Yes |
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 thei
smallest elements ofA
.A[i:n-1]
contains then - i
largest elements ofA
sorted.
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_DOWN
onA[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 - 2
elements ofA
in sorted order. ThusA
is 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).