Heap Sort
Heap Sort
Heap sort leverages the binary heap data structure to sort an array in O(n log n) time. It first transforms the array into a max-heap, then repeatedly extracts the maximum element and places it at the end. Unlike merge sort, heap sort works in-place with O(1) extra space, and unlike quicksort, it guarantees O(n log n) worst-case performance.
How It Works
- Build a max-heap from the input array. A max-heap is a complete binary tree where every parent is greater than or equal to its children.
- Extract the maximum: Swap the root (largest element) with the last element of the heap.
- Reduce heap size by one (the extracted element is now in its final position).
- Heapify the root: Restore the heap property by sifting the new root down.
- Repeat steps 2-4 until the heap is empty.
Understanding Heapify
The heapify (or sift-down) operation is the core of heap sort. Given a node that may violate the heap property, it compares the node with its children and swaps it with the larger child, continuing downward until the heap property is restored.
For an array representation of a binary heap:
- Parent of index
iis at(i - 1) // 2 - Left child of index
iis at2 * i + 1 - Right child of index
iis at2 * i + 2
Step-by-Step Example
Given [4, 10, 3, 5, 1]:
- Build max-heap: Start from the last non-leaf node and heapify down →
[10, 5, 3, 4, 1] - Extract max: Swap
10with1→[1, 5, 3, 4, | 10]. Heapify →[5, 4, 3, 1, | 10] - Extract max: Swap
5with1→[1, 4, 3, | 5, 10]. Heapify →[4, 1, 3, | 5, 10] - Extract max: Swap
4with3→[3, 1, | 4, 5, 10]. Heapify →[3, 1, | 4, 5, 10] - Extract max: Swap
3with1→[1, | 3, 4, 5, 10]. Done →[1, 3, 4, 5, 10]
Code Snippet
def heap_sort(numbers: list[int]) -> list[int]:
"""Sort using a max-heap built in-place."""
array_length = len(numbers)
def heapify(heap_size: int, root_index: int) -> None:
"""Sift down the element at root_index to restore heap property."""
largest = root_index
left_child = 2 * root_index + 1
right_child = 2 * root_index + 2
if left_child < heap_size and numbers[left_child] > numbers[largest]:
largest = left_child
if right_child < heap_size and numbers[right_child] > numbers[largest]:
largest = right_child
if largest != root_index:
numbers[root_index], numbers[largest] = numbers[largest], numbers[root_index]
heapify(heap_size, largest)
# Build max-heap (start from last non-leaf node)
last_non_leaf = array_length // 2 - 1
for i in range(last_non_leaf, -1, -1):
heapify(array_length, i)
# Extract elements one by one
for end in range(array_length - 1, 0, -1):
numbers[0], numbers[end] = numbers[end], numbers[0]
heapify(end, 0)
return numbers
Complexity Analysis
Time Complexity: O(n log n)
- Build heap: O(n) — this is tighter than the naive O(n log n) bound because most nodes are near the bottom and require few sift-down steps.
- Extract all elements: n-1 extractions, each requiring O(log n) heapify operations.
- Total: O(n) + O(n log n) = O(n log n) in all cases (best, average, worst).
Space Complexity: O(1)
Heap sort operates entirely in-place on the input array. The only extra space used is for index variables and the recursive call stack of heapify (which can be made iterative for strict O(1)).
When to Use Heap Sort
- Guaranteed O(n log n): When you cannot tolerate quicksort's O(n²) worst case (e.g., adversarial input in competitive settings).
- Memory-constrained environments: Only O(1) extra space, unlike merge sort's O(n).
- Priority queue extraction: If you've already built a heap for other purposes, extracting in sorted order is natural.
- Embedded systems: Predictable performance and minimal memory make it suitable for resource-constrained devices.
When to Avoid It
- Cache performance matters: Heap sort's access pattern jumps between parent and child nodes, causing poor cache locality. Quicksort and merge sort typically outperform it on modern CPUs due to sequential access patterns.
- Stability required: Heap sort is not stable — equal elements may be reordered.
- Small arrays: The overhead of building a heap isn't worth it for small n; insertion sort is simpler and faster.
Key Properties
| Property | Value |
|---|---|
| In-place | Yes |
| Stable | No |
| Adaptive | No |
| Worst-case guarantee | Yes — always O(n log n) |