![](https://img2018.cnblogs.com/blog/1853166/202001/1853166-20200127184321835-1396957852.png) ![](https://img2018.cnblogs.com/blog/1853166/202001/1853... ...
class Heap {
constructor (data) {
this.data = data
}
sort () {
let iArr = this.data
let n = iArr.length
if (n <= 1) {
return iArr
} else {
// 迴圈是為了遍歷每一個可能要調整的節點,maxHeapify內部遞歸是為了回覆被破壞的堆
for (let i = Math.floor(n / 2); i >= 0; i--) {
Heap.maxHeapify(iArr, i, n)
}
for (let j = 0; j < n; j++) {
Heap.swap(iArr, 0, n - 1 - j)
Heap.maxHeapify(iArr, 0, n - 1 - j - 1)
}
return iArr
}
}
static swap (arr, a, b) {
if (a === b) {
return ''
}
// 交換
let c = arr[a]
arr[a] = arr[b]
arr[b] = c
}
// 構建最大堆
static maxHeapify (Arr, i, size) {
// 左節點
let l = i * 2 + 1
// 右節點
let r = i * 2 + 2
let largest = i
// 父節點和左節點l作比較獲取最大
if (l <= size && Arr[l] > Arr[largest]) {
largest = l
}
// 右節點額最大值比較
if (r <= size && Arr[r] > Arr[largest]) {
largest = r
}
if (largest !== i) {
Heap.swap(Arr, i, largest)
Heap.maxHeapify(Arr, largest, size)
}
}
}
export default Heap