Why is the heap setup for loop using let i = Math.floor(n / 2) - 1; are the initial value. Its appears to be an optimized solution. Using let n = 0; provides the same solution, just dont understand the significance of this initial value
function maxHeapify(arr, n, i) {
let max = i;
const left = 2 * i + 1;
const right = 2 * i + 2;if (left < n && arr[max] < arr[left]) {
max = left;
}if (right < n && arr[max] < arr[right]) {
max = right;
}if (max !== i) {
[arr[i], arr[max]] = [arr[max], arr[i]]
maxHeapify(arr, n, max)
}
}function makeHeap(arr) {
let n = arr.length;
// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i–) {
maxHeapify(arr, n, i);
}
// Perform heap sort
for (let i = n - 1; i > 0; i–) {
[arr[i], arr[0]] = [arr[0], arr[i]]; // swap root with the last element
n–;
maxHeapify(arr, i, 0); // Heapify root element
}
return arr;
}
Also how would the code vary to work with a min heap instead or max heap?
Thanks in advanced!
Course: Educative: Interactive Courses for Software Developers
Lesson: Heap Sort (Implementation) - Mastering Data Structures and Sorting Algorithms in JavaScript