Heap Sort

medium

Given an integer array arr, return it sorted in ascending order using heap sort.

The idea: build a heap, then repeatedly remove the extreme element. The in-place version builds a max-heap and swaps the maximum to the back of the array on each step, shrinking the heap — sorting with O(1) extra space.

Hints

Build a max-heap so the largest element is at index 0.
Swap the root to the last position and shrink the heap, then re-heapify the root.
Sift-down must operate on the shrinking heap size, not the whole array.

Common doubts

Each round places the current maximum at the end of the unsorted region, so the array fills from the right with the largest remaining values — ascending overall.
In place, the extreme element goes to the back. A max-heap sends the largest to the back (ascending); a min-heap would produce descending.
Guaranteed O(n log n) like merge sort but O(1) space, and no O(n²) worst case like quicksort — though it isn't stable and has poorer cache behaviour.

Interview follow-ups

No — equal elements can be reordered by the sift-down swaps.
Build a min-heap and swap the min to the back each round.

Fun facts

  • Heap sort was the original application Williams designed the binary heap for in 1964.
  • Its O(1) space and guaranteed O(n log n) make it a favourite for embedded and real-time systems.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: arr = [4, 10, 3, 5, 1]
Output: [1, 3, 4, 5, 10]
Build a max-heap, then swap each maximum to the back.
Example 2
Input: arr = [5, 4, 3, 2, 1]
Output: [1, 2, 3, 4, 5]
Sorted ascending.
Constraints

- 0 <= arr.length <= 10^5 - -10^9 <= arr[i] <= 10^9

Solve this problem →