1. Array size
n is the full heap size before extraction begins.
const n = arr.lengthTyporithm · hard
Step 1 of 8 · intro card
Sorting Algorithms
Heap Sort builds a max heap, repeatedly moves the largest value to the end, and restores the heap.
A max heap keeps the largest value at index 0.
The build phase heapifies parent nodes from the bottom up.
The extraction phase swaps the root with the last unsorted value.
After each swap, the heap size shrinks and heapify restores the max-heap property.
Heap Sort is in-place and O(n log n), but it is not stable by default.
Build a max heap first.
Swap the root into the sorted tail.
Heapify the smaller heap after each extraction.
O(n log n) time in all main cases.
O(1) extra space, unstable by default.
function heapSort(arr) {
const n = arr.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (let end = n - 1; end > 0; end--) {
[arr[0], arr[end]] = [arr[end], arr[0]];
heapify(arr, end, 0);
}
return arr;
}
function heapify(arr, heapSize, root) {
let largest = root;
const left = 2 * root + 1;
const right = 2 * root + 2;
if (left < heapSize && arr[left] > arr[largest]) largest = left;
if (right < heapSize && arr[right] > arr[largest]) largest = right;
if (largest !== root) {
[arr[root], arr[largest]] = [arr[largest], arr[root]];
heapify(arr, heapSize, largest);
}
}Connect each part of the code to the concept before you type.
n is the full heap size before extraction begins.
const n = arr.lengthStart from the last parent and heapify upward to build a max heap.
for (let i = Math.floor(n / 2) - 1; i >= 0; i--)Each pass moves the current largest value to the end.
for (let end = n - 1; end > 0; end--)The max heap root is swapped into its final sorted position.
[arr[0], arr[end]] = [arr[end], arr[0]]Heapify only the remaining unsorted prefix.
heapify(arr, end, 0)Start by assuming the root is already the largest among parent and children.
let largest = rootArray heaps compute the left child from the parent index.
const left = 2 * root + 1The right child can replace the largest candidate if it exists and is greater.
right < heapSize && arr[right] > arr[largest]After swapping, heapify continues where the moved value landed.
heapify(arr, heapSize, largest)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
This version uses recursive sift-down frames and one swap temporary. Iterative sift-down can use O(1). The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state