Back to Benchmark

Heap Sort - O(n log n) Complexity

Understanding how heap sort achieves linearithmic time using binary heaps

What is Heap Sort?

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It works by building a max-heap from the array, then repeatedly extracting the maximum element and placing it at the end of the sorted portion.

Key Characteristics:

  • Uses Binary Heap: Leverages heap data structure properties
  • In-Place: Sorts array in place, O(1) extra space
  • Guaranteed O(n log n): Always O(n log n) regardless of input
  • Not Stable: May change relative order of equal elements

Think of it like organizing a tournament bracket - build a heap (tournament tree), find the winner (maximum), remove them, and repeat!

Trees and Heaps

Binary Heap Structure

A binary heap is a complete binary tree stored in an array:

  • Root at index 0
  • For node at index i:
    • Left child: 2i + 1
    • Right child: 2i + 2
    • Parent: ⌊(i-1)/2⌋
  • Max-heap: parent ≥ children (for heap sort)

Heap Properties

In a max-heap, the largest element is always at the root. This property allows us to efficiently find and extract the maximum element, which is the key to heap sort's efficiency.

How Does Heap Sort Work?

1. Build Max Heap

Convert the array into a max-heap by heapifying all non-leaf nodes starting from the bottom. This takes O(n) time.

2. Extract Maximum

Swap the root (maximum element) with the last element of the heap. The maximum is now in its correct sorted position at the end.

3. Reduce Heap Size

Decrease the heap size by one (excluding the sorted element) and heapify the root to restore the max-heap property.

4. Repeat Until Sorted

Repeat steps 2-3 until the heap is empty. Each extraction takes O(log n) time:

Build heap: O(n) - one-time operation
Extract n elements: n × O(log n) = O(n log n)
Total: O(n log n)
Interactive Heap Sort Visualization
Watch how heap sort builds a heap and extracts elements!

Array Representation

Code Example:

// Heap Sort - O(n log n) guaranteed
function heapSort(arr) {
  const n = arr.length;

  // Build max heap - O(n)
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
    heapify(arr, n, i);
  }

  // Extract elements - O(n log n)
  for (let i = n - 1; i > 0; i--) {
    [arr[0], arr[i]] = [arr[i], arr[0]]; // Move root to end
    heapify(arr, i, 0); // Heapify reduced heap
  }
}

function heapify(arr, n, i) {
  let largest = i;
  const left = 2 * i + 1;
  const right = 2 * i + 2;

  if (left < n && arr[left] > arr[largest]) largest = left;
  if (right < n && arr[right] > arr[largest]) largest = right;

  if (largest !== i) {
    [arr[i], arr[largest]] = [arr[largest], arr[i]];
    heapify(arr, n, largest); // Recursive heapify
  }
}
Built-in Functions for Sorting
Most programming languages provide built-in sorting functions. While heap sort is less commonly used directly, it's often part of hybrid sorting algorithms

Why is Heap Sort O(n log n)?

1. Building Heap: O(n)

Building a heap from an array takes O(n) time, not O(n log n). This is because we heapify from the bottom up, and most nodes are near the bottom (requiring fewer swaps).

2. Extracting Elements: O(n log n)

We extract n elements from the heap:

Each extraction: O(log n) - heapify root
n extractions: n × O(log n) = O(n log n)
This dominates the time complexity

3. Total Complexity

Combining both phases:

Build heap: O(n)
Extract elements: O(n log n)
Total: O(n log n)
Since O(n log n) > O(n), the total is O(n log n)

💡 Why O(n log n) is Guaranteed

Unlike quicksort, heap sort always performs O(n log n) regardless of input order. The heap structure ensures balanced operations, making it predictable and reliable.

Time Complexity Comparison
AlgorithmBestAverageWorstSpaceStable
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Real-World Examples

💾 Memory-Constrained Systems

Heap sort's O(1) space complexity makes it ideal for embedded systems and memory-constrained environments where merge sort's O(n) space is too expensive.

🔄 Hybrid Sorting Algorithms

Many modern sorting implementations (like Introsort in C++) use heap sort as a fallback when quicksort would degrade to O(n²), ensuring guaranteed O(n log n) performance.

🎯 Priority Queue Sorting

When data is already in a heap (priority queue), extracting elements in sorted order is essentially heap sort, making it natural for systems that maintain heaps.

📊 Real-Time Systems

Systems requiring guaranteed O(n log n) performance without the space overhead of merge sort use heap sort. Its predictable performance makes it suitable for real-time applications.

🔧 System Programming

Operating systems and low-level libraries use heap sort when memory efficiency is critical and worst-case performance must be guaranteed.

Key Takeaways
  • Heap sort is O(n log n) - guaranteed

    Always O(n log n) regardless of input order - predictable and reliable

  • O(1) space complexity

    Sorts in place with only O(1) extra space - most space-efficient O(n log n) sort

  • Uses binary heap structure

    Leverages heap properties to efficiently find and extract maximum elements

  • Not stable but guaranteed performance

    May change relative order of equal elements, but always performs O(n log n)

Practice Exercises
Test your understanding of heap sort with these exercises. Try to solve them yourself before checking the answers!