How it works?
Lesson 3 of 9 in Coddy's Heap Sort - DSA Series course.
A binary heap lives in a plain array. For the node at index i (0-based), its children are at 2*i + 1 and 2*i + 2. That indexing is the whole trick that lets a tree live in an array.
Step-by-Step Process:
- Build a max-heap: rearrange the array so every parent is >= its children. The largest value ends up at index 0.
- Extract the max: swap the root (largest) with the last element of the heap, then shrink the heap by one so the largest is now parked at the end in its final sorted position.
- Repair with sift-down: the new root may be out of place, so sift it down (swap it with its larger child, repeat) until the heap property holds again.
- Repeat until the heap is empty. The array is now sorted ascending.
Example on [4, 10, 3, 5, 1]:
- Build a max-heap: [10, 5, 3, 4, 1].
- Swap root 10 to the end and sift down, then repeat for 5, 4, 3.
- Result: [1, 3, 4, 5, 10].
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Heap Sort - DSA Series
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)