Sorting

Heap Sort

Size:15
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 148Start
Line 1
Starting Heap Sort on array of 15 elements.
Comparisons0
Swaps0
Operations0

Overview & Concept

Heap Sort is an efficient, comparison-based, in-place sorting algorithm that uses a Binary Max-Heap. It first organizes the array into a max-heap where the largest item is at the root, then repeatedly extracts the root by swapping it with the last element and restoring the heap property via sift-down.

How It Works

Heapify Construction: Converts the array into a Max-Heap in linear O(n) time.

Extract Maximum: Swaps root A[0] with last leaf A[end].

Sift-Down Rebalance: Sifts the new root down to restore the heap property in O(log n) time.

Shrink Heap: Decrements heap size and repeats until the entire array is sorted in ascending order.

Step-by-Step Execution

1. Build Max-HeapCall siftDown on all parent nodes from Math.floor(n/2) - 1 down to 0 in O(n) time.
2. Swap Root with LastSwap root A[0] (current maximum) with element at A[end].
3. Sift Down RootRestore max-heap property on subarray A[0..end-1].
4. Decrement & RepeatDecrement end by 1; repeat until heap size is 1.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n log n)O(n log n)O(n log n)O(1)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure heapSort(A):
  buildMaxHeap(A) from floor(n/2)-1 down to 0
  heapify(root):
    compare left child with root
    compare right child with current largest
    if largest != root: swap and heapify child
  for i = n - 1 down to 1:
    swap(A[0], A[i]) // extract max to end
    heapify(0) on heap of size i
  return A
Algorithmic Invariants
  • Heap Order Invariant: At start of each extraction, A[0..end] satisfies max-heap property: parent ≥ children.
  • Suffix Sorted Invariant: Elements A[end+1..n-1] are sorted and strictly greater than all elements in A[0..end].
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •Guaranteed O(n log n) time complexity in all cases (best, average, worst).
  • •In-place sorting: requires strictly O(1) auxiliary space (superior to Merge Sort in space).
  • •Zero risk of O(n²) worst-case degradation (unlike Quick Sort).

Trade-offs & Limitations

  • •Unstable sort.
  • •Poor cache locality compared to Quick Sort because sift-down jumps between distant indices (2i + 1).

Real-World Applications

Introsort Fallback

C++ std::sort switches from Quick Sort to Heap Sort if recursion depth exceeds 2 log n to guarantee O(n log n).

Embedded & Safety-Critical Systems

Avionics and automotive control systems requiring strict O(1) memory and O(n log n) time limits.

Decision Guide: When to Use

Ideal Scenarios

  • ✓When guaranteed O(n log n) worst-case time is mandatory AND auxiliary memory must be strictly O(1).

Consider Alternatives When

  • ✕When stable sorting is needed.
  • ✕When maximizing CPU cache throughput on standard consumer CPUs (Quick Sort is typically 2-3x faster).

Compare trade-offs and complexity across complementary tools in AlgoViz.