DSA
    intermediate

    Heap Sort

    Heap Sort

    A comparison-based sorting algorithm that uses a Binary Heap data structure. It divides its input into a sorted and an unsorted region, and iteratively shrinks the unsorted region by extracting the largest element.

    ⏱ O(n log n)
    💾 O(1)
    Ready
    idx: 0, val: 15
    15
    idx: 1, val: 64
    64
    idx: 2, val: 53
    53
    idx: 3, val: 96
    96
    idx: 4, val: 95
    95
    idx: 5, val: 74
    74
    idx: 6, val: 66
    66
    idx: 7, val: 41
    41
    idx: 8, val: 76
    76
    idx: 9, val: 20
    20

    Starting Heap Sort

    50%
    Live Variables
    n10

    Sort with a heap

    Sequence

    Order the steps of in-place heap sort.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What is the "Heap Property" in a Max Heap?

    The short version

    Think of a corporate hierarchy where the boss (largest number) is always at the top. To sort, you repeatedly 'retire' the boss and promote the next best candidate to the top position.

    In more depth

    Structure from Chaos

    Heap Sort turns the array into a Binary Heap first. This structure allows us to efficiently pull out the largest (or smallest) element repeatedly.

    The Process:

    1.Heapify: Transform the array into a Max Heap. Now the largest element is at the root (index 0).
    2.Extract: Swap the root with the last element. The largest item is now sorted at the end.
    3.Restore: "Sink" the new root down to restore the heap property.
    4.Repeat: Do this until the heap is empty.

    Why use it?

    It combines the best of both worlds: the O(n log n) guarantee of Merge Sort and the O(1) space efficiency of Quick Sort. However, it is not stable and generally slower in practice due to poor cache locality.

    When to reach for this

    • When **O(1) Space** complexity is a strict requirement
    • When you need guaranteed **O(n log n)** time complexity
    • Embedded systems or environments with limited memory

    Interview Questions

    Google
    Amazon
    Microsoft
    Airbnb
    Bloomberg
    Facebook
    Apple
    Uber
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required