Heap Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Heap Sort
An elegant comparison-based sorting algorithm that organizes data into a binary heap to extract elements in sorted order efficiently and in-place.
How it works
Heap Sort utilizes a binary heap data structure. First, the algorithm transforms the input array into a **Max Heap** where each parent node is greater than or equal to its children. Once the heap is established, the root element (which is guaranteed to be the largest) is swapped with the last element of the array. The active heap size is then reduced by one, and a heapify operation is performed on the root to restore the heap property. This process repeats until the heap is empty, leaving a fully sorted array.
- Interpret the array as a binary tree.
- Build a Max Heap in-place starting from the lowest parent node up to the root (index
0). - Swap the root (index
0) with the last element of the active unsorted range. - Decrease the active unsorted range size by 1.
- Perform **Heapify** at the root to bubble the new root down to its correct heap position.
- Repeat steps 3–5 until the active range size is 1.
Complexity
Interactive visualization
Pseudocode
procedure heapSort(A): n ← length(A) for i from ⌊n/2⌋ − 1 down to 0: heapify(A, n, i) for i from n − 1 down to 1: swap A[0], A[i] heapify(A, i, 0) procedure heapify(A, size, i): largest ← i left ← 2i + 1 right ← 2i + 2 if left < size and A[left] > A[largest]: largest ← left if right < size and A[right] > A[largest]: largest ← right if largest ≠ i: swap A[i], A[largest] heapify(A, size, largest)
JavaScript implementation
function heapSort(arr) { const n = arr.length; for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { heapify(arr, n, i); } for (let i = n - 1; i > 0; i--) { [arr[0], arr[i]] = [arr[i], arr[0]]; heapify(arr, i, 0); } return arr; } function heapify(arr, size, idx) { let largest = idx; const left = 2 * idx + 1; const right = 2 * idx + 2; if (left < size && arr[left] > arr[largest]) largest = left; if (right < size && arr[right] > arr[largest]) largest = right; if (largest !== idx) { [arr[idx], arr[largest]] = [arr[largest], arr[idx]]; heapify(arr, size, largest); } }
Pros and cons
Pros
- Guaranteed O(n log n) performance even in the worst case.
- In-place: requires only O(1) auxiliary space.
- No recursion stack issues if written iteratively.
- Great for streaming inputs where top element is continuously needed.
Cons
- Unstable: swaps values across large distances, breaking order of duplicates.
- Poor cache locality: accesses children at index `2i+1` and `2i+2` which are far in memory.
- Larger constant factor than Quick Sort in practice.
- Difficult to parallelize.
When to use it
- Systems with hard real-time latency limits: guarantees O(n log n) without Quick Sort's degradation.
- Memory-constrained systems: when O(log n) extra space of Quick Sort or O(n) of Merge Sort cannot be allocated.
- Finding the k-largest elements: can be stopped early after k root extractions, running in O(n + k log n) time.
Related reading
Sleep Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A unique concurrency-based sorting algorithm: spawns a separate thread for each element, sleeping for a duration proportional to the element value before writing it to the output.
By Md. Harun-Or-Roshid
Cube Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A parallel dimension sorting algorithm: organizes elements in a 3D coordinate cube and sorts vectors along the height, width, and depth axes sequentially to achieve sorted order.
By Md. Harun-Or-Roshid
Patience Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A card-game inspired sorting algorithm: distributes elements onto a series of piles such that each pile's top is \(\ge\) the incoming value, then performs a multi-way merge across pile tops.
By Md. Harun-Or-Roshid
Library Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A gapped variation of Insertion Sort: leaves empty slots (gaps) in the array, allowing elements to be inserted in \(O(1)\) shift time on average by avoiding massive shifts.
By Md. Harun-Or-Roshid