What is heap-sort, and why does it run in $O(n \log n)$?
Heap-sort is PQ-Sort with a heap-based priority queue: insert all $n$ elements, then remove them all with removeMin(). Each operation costs $O(\log n)$, so the total is about $2n \log n$, i.e. $O(n \log n)$.
| Phase | Work | Cost |
|---|---|---|
| 1. Build | $n$ × insert() |
$n \cdot O(\log n)$ |
| 2. Drain | $n$ × removeMin() |
$n \cdot O(\log n)$ |
| Total | $O(n \log n)$ |
The improvement over the list-based variants comes from balancing the work. The unsorted list made inserts free and removals linear; the sorted list did the opposite; both ended at $O(n^2)$. The heap makes both operations logarithmic, because each only walks one root-to-leaf path in a tree of height $O(\log n)$.
The gap is large even for small inputs. With 1000 elements, $n^2$ is $10^6$ steps while $n \log_2 n$ is about $1000 \cdot 10 = 10^4$: a factor of 100. The factor itself grows with $n$ (roughly 200 at 2000 elements, 400 at 4000), and for a million elements it is $10^{12}$ against about $2 \cdot 10^7$.
Going further: the classic heap-sort works in place inside the input array (the heap occupies the front, the sorted output grows at the back) and can build the initial heap bottom-up in $O(n)$ instead of $O(n \log n)$. The overall bound stays $O(n \log n)$, because draining still takes $n$ removeMins.
Go deeper:
Heapsort — the in-place version with bottom-up heap construction, and how it compares with quick- and merge-sort.
Heap sort visualization (USFCA) — watch the heap being built and drained inside a single array.