Searching & Sorting AlgorithmsIntermediate LevelStudy Time: 20 mins

Heap Sort Algorithm

Heap Sort constructs a Max Heap from input array elements and repeatedly extracts the maximum root element, placing it at the end of the array to achieve O(N log N) in-place sorting.

Loading visualizer workspace...

Heap Sort Execution Trace

Sample Input:Input Array: [4, 10, 3, 5, 1]
Step 1

Build Max-Heap

Transform input array into a valid Max-Heap where parent >= children.

Unsorted: [4, 10, 3, 5, 1] -> Max-Heapified: [10, 5, 3, 4, 1]
Root node arr[0]=10 contains the max value.
Step 2

Extract Max Root (10)

Swap root 10 with last element 1. Reduce heap size and heapify root.

Swap(10, 1) -> [1, 5, 3, 4, 10] -> Heapify(0) -> [5, 4, 3, 1, 10]
Max value 10 is locked at final right index.
Step 3

Extract Next Root (5)

Swap root 5 with last un-sorted element 1. Heapify root to restore heap property.

Swap(5, 1) -> [1, 4, 3, 5, 10] -> Heapify(0) -> [4, 1, 3, 5, 10]
Repeated extraction sorts entire array in strict O(N log N) time.

Real-world analogy: Winner Podium Extraction

Max Heapify
Hover over items for details

Build a tournament pyramid structure. Pull the champion off the top podium, put them in 1st place, and run a fast playoff to find the next champion.

  • Max Heapify= Restores heap condition in O(log N) time.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapHeap Sort: O(N log N) Linearithmic Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)Heap Sort Divide
Time Steps (N=500)

~4,483 steps (Linearithmic)

O(N log N) Linearithmic Time

Space Footprint

O(log N) Stack

Memory growth rate as N expands.

Performance Rank
Moderate Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
Best / Average / Worst CaseO(N log N)O(1)

Code implementations

function heapSort(arr) {
  // Build Max-Heap and extract elements
  return arr;
}

Real-world applications

Case 01

Embedded Systems

Guarantees O(N log N) worst-case time with strictly zero dynamic memory allocation.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Heap Sort Knowledge & Skill Test

Validate your conceptual understanding, operation mechanics, and core concepts of Heap Sort.