Heapsort
Overview
Heapsort uses a max-heap to build a heap from an array and repeatedly extract the max element, producing a sorted array when finished.
| Property | Value |
|---|---|
| Best Case | |
| Worst Case | |
| Avg. Case | |
| Aux. Memory | |
| Stable | No |
| Adaptive | Yes |
| Visualization | ![]() |
Loop Invariant
Heapsort has loop invariant
A[0:i-1]is a max-heap containing theismallest elements ofA.A[i:n-1]contains then - ilargest elements ofAsorted.
We prove
- 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
