class HeapSort {
static heapify(arr, n, i) {
let largest = i; // Initialize largest as root
const left = 2 * i + 1; // left child index
const right = 2 * i + 2; // right child index
// If left child is larger than root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If largest is not root
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]]; // swap
// Recursively heapify the affected subtree
HeapSort.heapify(arr, n, largest);
}
}
static sort(arr) {
const n = arr.length;
// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
HeapSort.heapify(arr, n, i);
}
// One by one extract elements
for (let i = n - 1; i > 0; i--) {
// Move current root to end
[arr[0], arr[i]] = [arr[i], arr[0]];
// call max heapify on the reduced heap
HeapSort.heapify(arr, i, 0);
}
}
}
// Driver code
const array = [4, 10, 3, 5, 1];
HeapSort.sort(array);
console.log(array.join(", ") + "\n");if (left < n && arr[left] > arr[largest]) { largest = left; }
Check if left child is larger than current largest
if (right < n && arr[right] > arr[largest]) { largest = right; }
Check if right child is larger than current largest
if (largest !== i) { swap arr[i] and arr[largest]; heapify(arr, n, largest); }
Swap root with largest child and heapify subtree
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { heapify(arr, n, i); }
Build max heap from bottom up
for (let i = n - 1; i > 0; i--) { swap arr[0] and arr[i]; heapify(arr, i, 0); }
Extract max element and restore heap