Heap sort treats the array as a complete binary tree, first sifting each internal node down until every parent is at least as large as its children, then repeatedly swapping the root — the maximum — to the end and shrinking the heap by one. Both phases work in place and the extractions are bounded by O(n log n), so heapsort sorts with no extra memory.
The max-heap property
- Every parent is at least as large as its children: a[i]≥a[2i+1] and a[i]≥a[2i+2].
- Build the heap by sifting down every internal node, from the last one back to the root.
- Sifting down swaps a node with its larger child until the property holds again.
Sifting down
- A sift-down follows one root-to-leaf path, so it touches at most ⌊log2n⌋ levels.
- At each level the node is compared with its two children: at most two comparisons.
- After a swap, the subtree below the previous root already satisfies the heap property.
Extracting the maximum
- The root holds the maximum; swapping it to the end of the shrinking heap fixes its final position.
- The new root is then sifted down to restore the heap property.
- The sorted suffix grows from the right, one element per extraction.
Why O(n log n)
- Building the heap with bottom-up sift-downs is O(n), not O(nlogn).
- Each of the n−1 extractions sifts down at most ⌊log2n⌋ levels.
- Total: O(n)+O(nlogn)=O(nlogn), in the worst case and in place.
The sorted suffix
- After each extraction the element left at the end is final and is marked sorted.
- Once the heap holds a single element the whole array has been marked.
- The last element never needs a comparison — it is the only one left.