Home
DSA Visualizer
Sorting
Heap Sort
Heap Sort
Heap sort is a selection-based sorting algorithm that uses a binary heap to find the maximum element efficiently.
Intuition
Imagine a corporate hierarchy where the boss (largest number) must always be at the top. We repeatedly remove the boss, send them to retirement (sorted end), and promote a new boss, adjusting the hierarchy until everyone is retired (sorted).
Concept
- Max Heap: A binary tree where Parent >= Children. Root is always the Max.
- Heapify: The process of restoring the heap property after the root changes.
- In-Place: Uses the same array to store the heap and the sorted result.
How it Works
Algorithm:
- Build a Max Heap from the input array.
- Swap the Root (Max) with the last element.
- Reduce heap size by 1 (the last element is now sorted).
- Heapify the new Root to restore Max Heap property.
Step-by-Step Breakdown
Watch the visualization:
- Blue bar (NODE): The subtree root being sifted down.
- Amber bars: The parent and child being compared.
- Red bars: A swap: fixing the heap property, or moving the max to the end.
- Green bars: Sorted elements at the end of the array.
When to Use
- Guaranteed O(N log N): Good worst-case performance unlike Quick Sort.
- Space Constraints: O(1) extra space.
- Priority Queues: Excellent for finding the 'Top K' items.
When NOT to Use
- Cache Performance: Poor locality of reference compared to Quick Sort.
- Stable Sort Required: It is unstable.
How to Identify
"Top K Elements", "Priority Queue", "Heaps".
Applying for software engineering roles? Free, no sign-up:
