Heap Sort
Idea Like You Are 10
Heap Sort uses a special tree shape called a heap.
In a max-heap:
- the biggest number is always at the top
So Heap Sort does this:
- Build a max-heap
- Take the biggest element from the top
- Put it at the end
- Fix the heap
- Repeat
Small Example
Sort:
After building a max-heap, the biggest value goes to the top.
One possible heap view:
Now swap the top with the last element:
Then fix the heap again with the remaining elements.
Keep repeating until sorted.
Diagram
Algorithm
- Convert the array into a max-heap
- Swap the first element with the last unsorted element
- Reduce heap size by one
- Heapify again
- Repeat
Pseudocode
Time Complexity
| Case | Time |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
Why This Time Complexity?
Building the heap takes O(n).
Then we remove the largest element n times, and each time fixing the heap takes about O(log n).
So total work is about:
That gives O(n log n).
Space Complexity
O(1) extra space for the common in-place version.
Performance
- Good guaranteed speed
- Does not need extra array space like Merge Sort
- Usually not as fast in practice as a good Quick Sort
When To Use
- When you want guaranteed
O(n log n)time - When you also want in-place sorting