`

JS 堆排序

阅读更多
function heapSort(arr) {
  var len = arr.length;
  function swap(arr, rootIndex, maxIndex) {
      var temp = arr[rootIndex];
      arr[rootIndex] = arr[maxIndex];
      arr[maxIndex] = temp;
  }
  function diff(arr, index) {
      var leftIndex = 2 * index + 1;
      var rightIndex = 2 * index + 2;
      var maxIndex = index;

      if (leftIndex < len && arr[leftIndex] > arr[maxIndex]) {
          maxIndex = leftIndex
      }
      if (rightIndex < len && arr[rightIndex] > arr[maxIndex]) {
          maxIndex = rightIndex
      }
      if (maxIndex !== index) {
          swap(arr, index, maxIndex);
          diff(arr, maxIndex);
      }
  }
  for (var i = Math.floor(len / 2); i >= 0; i--) {
      diff(arr, i)
  }
  for (var j = len - 1; j >= 0; j--) {
      len--;
      swap(arr, 0, j);
      diff(arr, 0);
  }
  return arr;
}

console.log(heapSort([-4, 8, 6, 3, 0, 2, 5, -1, 4, 1]));

 

效果图:


 

感谢大树的帮助。

 

 

 

 

 

 

 

  • 大小: 7 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics