我正在尝试在 Javascript 中实现堆排序,但是有一个undefined
元素,array.length - 2
并且索引 0 处的元素是未排序的。这是代码:
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);
for (var i = array.length; i >= 2; i--) {
swap(array, 1, i);
array.heapSize--;
maxHeap(array, 1);
}
};
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>
我想,array[i] == undefined
当i = array.length
. 我尝试修复此(设置i = array.length - 1
),但数组以完全不同的顺序出现。我还发现 0 从未交换过,因为 i 总是大于 0。我再次尝试,数组以完全不同的顺序出现。