Click "Build Heap" to start the step-by-step visualization of constructing a min heap from the array.
The algorithm works by heapifying each non-leaf node starting from the last non-leaf node and moving up to the root.
function buildMinHeap(arr) {
// Start from last non-leaf node and heapify each node
const n = arr.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
}
function heapify(arr, n, i) {
let smallest = i;
const left = 2 * i + 1;
const right = 2 * i + 2;
// Compare with left child
if (left < n && arr[left] < arr[smallest]) {
smallest = left;
}
// Compare with right child
if (right < n && arr[right] < arr[smallest]) {
smallest = right;
}
// If smallest is not the current node, swap and continue heapifying
if (smallest !== i) {
[arr[i], arr[smallest]] = [arr[smallest], arr[i]];
heapify(arr, n, smallest);
}
}