Skip to content

Visualizers

Heap Sort Visualizer

Step-through animation of Heap Sort showing max-heap creation and deletion.

native (Canvas API) Client-side
Ready to visualize

Execution Log

Comparisons: 0
Swaps: 0
Current Action:

Idle

Legend:

Unsorted
Active Heapify / Compare
Sorted

Heap Sort Algorithm

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It is an in-place algorithm but is not a stable sort.

How It Works

  1. Build a Max Heap from the input array. In a max heap, the parent node is always larger than or equal to its child nodes, making the root the largest element.
  2. Swap the root (largest element) with the last element of the heap. Reduce the heap size by 1.
  3. Heapify the root of the tree to restore max heap properties.
  4. Repeat steps 2-3 until the heap is empty, resulting in a sorted array.

Implementation

function heapSort(arr) {
  const n = arr.length;
  // Build max heap
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
    heapify(arr, n, i);
  }
  // Extract elements from heap one by one
  for (let i = n - 1; i > 0; i--) {
    const temp = arr[0];
    arr[0] = arr[i];
    arr[i] = temp;
    heapify(arr, i, 0);
  }
  return arr;
}

function heapify(arr, n, i) {
  let largest = i;
  const l = 2 * i + 1;
  const r = 2 * i + 2;
  
  if (l < n && arr[l] > arr[largest]) largest = l;
  if (r < n && arr[r] > arr[largest]) largest = r;
  
  if (largest !== i) {
    const swap = arr[i];
    arr[i] = arr[largest];
    arr[largest] = swap;
    heapify(arr, n, largest);
  }
}