Browse curriculum

Heap Sort

Heap sort is a selection-based sorting algorithm that uses a binary heap to find the maximum element efficiently.

Intuition

Imagine a corporate hierarchy where the boss (largest number) must always be at the top. We repeatedly remove the boss, send them to retirement (sorted end), and promote a new boss, adjusting the hierarchy until everyone is retired (sorted).

Concept

  • Max Heap: A binary tree where Parent >= Children. Root is always the Max.
  • Heapify: The process of restoring the heap property after the root changes.
  • In-Place: Uses the same array to store the heap and the sorted result.

How it Works

Algorithm:

  1. Build a Max Heap from the input array.
  2. Swap the Root (Max) with the last element.
  3. Reduce heap size by 1 (the last element is now sorted).
  4. Heapify the new Root to restore Max Heap property.

Step-by-Step Breakdown

Watch the visualization:

  • Blue bar (NODE): The subtree root being sifted down.
  • Amber bars: The parent and child being compared.
  • Red bars: A swap: fixing the heap property, or moving the max to the end.
  • Green bars: Sorted elements at the end of the array.

When to Use

  • Guaranteed O(N log N): Good worst-case performance unlike Quick Sort.
  • Space Constraints: O(1) extra space.
  • Priority Queues: Excellent for finding the 'Top K' items.

When NOT to Use

  • Cache Performance: Poor locality of reference compared to Quick Sort.
  • Stable Sort Required: It is unstable.

How to Identify

"Top K Elements", "Priority Queue", "Heaps".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

How does Heap Sort work?

Heap Sort works by first building a Max-Heap from the input data, then repeatedly swapping the root (largest element) with the last unsorted element and rebuilding the heap.


Is Heap Sort stable?

No, Heap Sort is not a stable sorting algorithm because the heap construction and extraction processes can swap equal elements across large distances.


Heap Sort vs Merge Sort?

Both are O(n log n), but Heap Sort works in-place (O(1) extra space), while Merge Sort is stable and often faster for linked lists.