Heap Sort
An in-place algorithm that rebuilds the array into a max-heap and repeatedly extracts the root (maximum) to sort. Guarantees O(n log n) even in the worst case.
01Heap Sort
Explore How It WorksStarting heap sort. Turn the array into a max heap so the largest value always sits on top, then pull that value off to the back one at a time.
Phase 1 · build the heap. Walk up from the last node that has children, making every parent larger than its children.
80 is larger than its child 40. This spot already satisfies the condition, so leave it.
30 is smaller than both children, 70 and 10. It has to trade places with the larger child, 70.
70 moves up and 30 moves down. The slot it lands in has no children, so we stop here.
Now the top. 50 is smaller than both children, 70 and 80, so it swaps with the larger one, 80.
80 rises to the top. The 50 that came down is larger than its new child 40, so it sinks no further.
The max heap is built. The top now holds 80, the largest value of all.
Phase 2 · extraction. Swap the top 80 with the last slot to lock it in, then drop that slot from the heap.
Rebuilding with what remains lifts 70 to the top. Lock it into the second-to-last slot the same way.
Rebuilding again puts 50 on top. Set it down in the third slot from the end.
This time the top is 40. Lock it into the next slot and shrink the heap further.
Finally lock in 30. Only one value is left in the heap.
Heap sort is done. Filling the array from the back with each maximum leaves it in ascending order.
02 Understand It Simply
For EveryoneBuilds a heap over the whole array, then repeatedly moves the maximum from the top to the end. Needs almost no extra memory.
Builds a heap, then repeatedly pops the max and fills from the back.
Guarantees O(n log n) with no extra memory.
- –Memory-constrained sorting
- –priority-based processing
03 Python Implementation
A clean, readable reference implementation of the core logic of Heap Sort.
04 Frequently Asked Questions
FAQWhat is Heap Sort?+
An in-place algorithm that rebuilds the array into a max-heap and repeatedly extracts the root (maximum) to sort. Guarantees O(n log n) even in the worst case.
What is the time complexity of Heap Sort?+
The time complexity of Heap Sort is O(n log n). Follow the step-by-step visualization to see exactly why.
Where is Heap Sort used?+
Memory-constrained sorting, priority-based processing.
What's a simple analogy for Heap Sort?+
Builds a heap over the whole array, then repeatedly moves the maximum from the top to the end. Needs almost no extra memory.
