Heap Sort Algorithm in Data Structure — Working, Implementation and Applications
Heap Sort is a comparison-based sorting algorithm that uses a Binary Heap data structure. It first builds a max-heap from the input data, then repeatedly extracts the maximum element and rebuilds the heap until the array is sorted.
How It Works
- Build a max-heap from the input array, so the largest element is at the root.
- Swap the root (maximum) with the last element of the heap.
- Reduce the heap size by one and 'heapify' the root to restore the max-heap property.
- Repeat until the heap size is 1 — the array is now sorted in ascending order.
def heapify(arr, n, i):
largest = i
left, right = 2 * i + 1, 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
return arr
Complexity
| Case | Time | Space |
|---|---|---|
| Best/Average/Worst | O(n log n) | O(1) |
Applications
- Systems requiring guaranteed O(n log n) worst-case performance (unlike Quick Sort).
- Priority queue implementations.
- Finding the k largest/smallest elements in a dataset.
- Used in embedded and real-time systems where predictable performance matters.
Why Heapifying Starts From the Middle
The build-heap loop begins at index n // 2 - 1 rather than at the start of the array. That index is the last node that has at least one child; everything after it is a leaf, and a single leaf is already a valid heap on its own. By heapifying backwards from this point toward the root, every node is fixed only after its children are already correct heaps, so each heapify call can safely sink a value into place.
This is why building the heap costs O(n) and not O(n log n). Most nodes sit near the bottom and sink only a level or two; the costly deep sinks happen for just a handful of nodes near the root.
A Short Dry Run
Take [4, 10, 3, 5, 1]. Building the max-heap rearranges it to [10, 5, 3, 4, 1]. Now swap the root 10 with the last slot to get [1, 5, 3, 4, 10], shrink the heap to the first four items, and heapify to get [5, 4, 3, 1]. Repeat: 5 moves to the end, then 4, then 3, leaving the array sorted as [1, 3, 4, 5, 10]. The sorted part grows from the right while the heap shrinks from the left, which is why no extra array is needed.
Heap Sort Compared With Quick Sort and Merge Sort
| Trait | Heap Sort | Quick Sort | Merge Sort |
|---|---|---|---|
| Worst case | O(n log n) | O(n squared) | O(n log n) |
| Extra memory | O(1) | O(log n) stack | O(n) |
| Stable | No | No | Yes |
Pick heap sort when a guaranteed upper bound and tiny memory use matter more than raw speed. In everyday sorting, quick sort usually runs faster because it touches memory in a more cache-friendly order, and merge sort is chosen when stability is required.
Mistakes to Watch For
- Forgetting that heap sort is not stable — equal keys can swap order, which matters when sorting records by one field.
- Using child indices
2*i+1and2*i+2with a one-based array; those formulas assume zero-based indexing. - Passing the full length to
heapifyduring extraction instead of the shrinking heap size, which pulls already-sorted values back in.
Takeaway: build once in linear time, then extract the maximum repeatedly. The whole method rests on keeping the max-heap property true after every swap.