我试图在javascript中实现heapsort,但是在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),但是数组出了一个完全不同的顺序。我还发现0从未被交换,因为我总是大于0。我又试了一次,数组的顺序完全不同。

最佳答案

您在JavaScript中使用的是基于1的索引,而不是基于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 >= 0; i--) {
      maxHeap(array, i);
    }
  };
  buildHeap(array);
  for (var i = array.length-1; i >= 1; i--) {
    swap(array, 0, i);
    array.heapSize--;
    maxHeap(array, 0);

    document.getElementById("getHeapSort").innerHTML = document.getElementById("getHeapSort").innerHTML + a + "<br>";
  }
};
var a = [55, 67, 10, 34, 25, 523, 1, -2];
document.getElementById("getHeapSort").innerHTML = a + "<br>";
heapSort(a);

这是一把小提琴:http://jsfiddle.net/mbL5enL5/1/

09-30 18:28