What is heapsort?
Why Interviewers Ask This
This is a classic screening question for Data Structures & Algorithms roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Heapsort is a comparison-based sorting algorithm that uses a binary max-heap. Algorithm: (1) Build max-heap: rearrange array into a valid max-heap in O(n) (call siftDown on all non-leaf nodes from bottom-up); (2) Sort: repeatedly extract the max (root), swap it with the last element, reduce heap size by 1, and sift down the new root: O(n log n) for n extractions. Time: O(n log n) all cases (best, average, worst — unlike quicksort which is O(n²) worst). Space: O(1) — in-place (unlike merge sort which needs O(n)). Stable: NO — relative order of equal elements may change. Practical performance: slower than quicksort in practice due to poor cache behavior (heap accesses are non-sequential). Heapsort is used when: guaranteed O(n log n) worst case is needed AND O(1) space is required (Introsort uses heapsort as fallback when quicksort depth exceeds O(log n) to avoid O(n²)). Build heap in O(n): call siftDown from index n/2-1 to 0 — most nodes are at the bottom where siftDown is O(1), amortizing to O(n) total. This is better than n×insert (each O(log n)) = O(n log n).
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Data Structures & Algorithms codebase.
Previous
What is a deque (double-ended queue)?
Next
What is the difference between depth and height of a tree?