Heap Sort

Pattern: Heap implementation

medium

Build a max heap in place. Then, n - 1 times, swap the top (the largest left) into the last unsorted slot, shrink the heap by one and sift the new top down. The array ends sorted ascending in O(n log n) time and O(1) extra space.

The problem

Sort an array ascending in place using a heap. [4, 1, 3, 9, 7] becomes [1, 3, 4, 7, 9]. The function returns nothing; the tests print the array.

Think first

  • Where is the largest value of a max heap?
  • Where does it belong in the sorted array?
  • What is left to fix after moving it there?

Hints

    Brute force, and why it fails

    Selection sort finds the maximum by scanning, O(n) each time: O(n²) in total.

    The key insight

    A max heap finds the maximum in O(1) and repairs itself in O(log n), so selection-sort's idea runs in O(n log n) without extra memory.

    Dry run

    90 
    71 
    32 
    13 
    44 

    arr = [4, 1, 3, 9, 7]. Build a max heap bottom-up.

    Step 1 of 4

    The plan

    build a max heap
    for end from n - 1 down to 1:
        swap arr[0], arr[end]
        siftDown(arr, 0, heap size = end)
    

    Complexity

    Time
    O(n log n)
    Space
    O(1)

    Building is O(n); each of the n - 1 extractions sifts in O(log n).

    Edge cases

    • One value.
    • Already sorted.
    • Duplicates: the result is sorted, but heap sort is not stable.
    I've built my logic, show the code

    Java

    class Solution {
        public void heapSort(int[] arr) {
            int n = arr.length;
            for (int i = n / 2 - 1; i >= 0; i--) siftDown(arr, i, n);   // build a max heap
            for (int end = n - 1; end > 0; end--) {
                int t = arr[0]; arr[0] = arr[end]; arr[end] = t;        // the max goes to the end
                siftDown(arr, 0, end);                                  // repair the heap that is left
            }
        }
    
        private void siftDown(int[] a, int i, int n) {
            while (true) {
                int l = 2 * i + 1, r = l + 1, big = i;
                if (l < n && a[l] > a[big]) big = l;
                if (r < n && a[r] > a[big]) big = r;
                if (big == i) return;
                int t = a[big]; a[big] = a[i]; a[i] = t;
                i = big;
            }
        }
    }

    C++

    class Solution {
    public:
        void heapSort(vector<int>& arr) {
            int n = static_cast<int>(arr.size());
            for (int i = n / 2 - 1; i >= 0; i--) siftDown(arr, i, n);   // build a max heap
            for (int end = n - 1; end > 0; end--) {
                swap(arr[0], arr[end]);                                 // the max goes to the end
                siftDown(arr, 0, end);                                  // repair the heap that is left
            }
        }
    
        void siftDown(vector<int>& a, int i, int n) {
            while (true) {
                int l = 2 * i + 1, r = l + 1, big = i;
                if (l < n && a[l] > a[big]) big = l;
                if (r < n && a[r] > a[big]) big = r;
                if (big == i) return;
                swap(a[big], a[i]);
                i = big;
            }
        }
    };

    Python

    class Solution:
        def heapSort(self, arr: list[int]) -> None:
            n = len(arr)
            for i in range(n // 2 - 1, -1, -1):     # build a max heap
                self.sift_down(arr, i, n)
            for end in range(n - 1, 0, -1):
                arr[0], arr[end] = arr[end], arr[0]   # the max goes to the end
                self.sift_down(arr, 0, end)         # repair the heap that is left
    
        def sift_down(self, a: list[int], i: int, n: int) -> None:
            while True:
                l, r, big = 2 * i + 1, 2 * i + 2, i
                if l < n and a[l] > a[big]:
                    big = l
                if r < n and a[r] > a[big]:
                    big = r
                if big == i:
                    return
                a[big], a[i] = a[i], a[big]
                i = big

    Common mistakes

    • Sifting down over the whole array instead of the shrunk heap, which pulls sorted values back.
    • Building a min heap, which sorts descending with this loop.

    Similar problems