I have been working on implementing heapsort in JavaScript, but I've encountered an issue with an undefined
element at position array.length - 2
, and the element at index 0 is not sorted.
Here is the code snippet:
var heapSort = function(array) {
var swap = function(array, firstIndex, secondIndex) {
var temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
};
var maxHeap = function(array, i) {
var l = 2 * i;
var r = l + 1;
var largest;
if (l <= array.heapSize && array[l] > array[i]) {
largest = l;
} else {
largest = i;
}
if (r <= array.heapSize && array[r] > array[largest]) {
largest = r;
}
if (largest != i) {
swap(array, i, largest);
maxHeap(array, largest);
}
};
var buildHeap = function(array) {
array.heapSize = array.length;
for (var i = Math.floor(array.length / 2); i >= 1; i--) {
maxHeap(array, i);
}
};
buildHeap(array);
// Code further goes here...
};
var a = [55, 67, 10, 34, 25, 523, 1, -2];
heapSort(a);
document.getElementById("getHeapSort").innerHTML = a;
* {
font-family: Arial, sans-serif;
}
<p id="getHeapSort"></p>
I observed that the issue arises when array[i]
is undefined with i = array.length
. I attempted to address this by changing (setting i = array.length - 1
), but it resulted in an entirely different output order. Additionally, I noticed that elements at index 0 were never swapped due to the value of i always being greater than 0. Even after attempting to rectify this, the array still ended up in a completely different order.