使用原生 JavaScript 實現堆排序


堆排序基本上是一種基於比較的排序演算法。可以將其視作一種改進的選擇排序——與該演算法相似,它將其輸入劃分為已排序區域和未排序區域,並透過提取目標(最大或最小)元素並將其移至已排序區域以互動方式縮減未排序區域。

示例

程式碼如下 −

const constructHeap = (arr, ind) => {
   let left = 2 * ind + 1;
   let right = 2 * ind + 2;
   let max = ind;
   if (left < len && arr[left] > arr[max]) {
      max = left;
   }
   if (right < len && arr[right] > arr[max]) {
      max = right;
   }
   if (max != ind) {
      swap(arr, ind, max);
      constructHeap(arr, max);
   }
}
function swap(arr, index_A, index_B) {
   let temp = arr[index_A];
   arr[index_A] = arr[index_B];
   arr[index_B] = temp;
}
function heapSort(arr) {
   len = arr.length;
   for (let ind = Math.floor(len / 2); ind >= 0; ind −= 1) {
      constructHeap(arr, ind);
   }
   for (ind = arr.length − 1; ind > 0; ind−−) {
      swap(arr, 0, ind);
      len−−;
      constructHeap(arr, 0);
   }
}
const arr = [3, 0, 2, 5, −1, 4, 1];
heapSort(arr);
console.log(arr);
var len;

輸出

控制檯中的輸出將為 −

[
   −1, 0, 1, 2,
   3, 4, 5
]

更新時間:2020-11-23

178 次瀏覽

啟動你的 職業生涯

獲得認證,完成課程

開始學習
廣告