堆排序
- 最大堆(儿子皆小于双亲)
- 最小堆(双亲皆小于儿子)
堆建立
- 构建堆调整函数(调整范围,索引以下的部分,至少包含子结点)
- 构建的位置是最后叶子节点的双亲
- 最后叶子的双亲计算 (len / 2)- 1
- 从后往前,从下往上,确保最小堆的最小值的精准性,保证扫描范围的全面性。
堆取值
- 取值后会产生缺值的现象:(1)填值(2)重构
- 填值只需要单次调整,即可恢复最小堆
堆实现
class Heap
{
constructor (heapArr)
{
this.heap = heapArr
}
setHeapVal = (key, val) => this.heap[key] = val
adjustMaxHeap (sta, end)
{
let temp = this.heap[sta]
for (let i = 2 * sta + 1; i < end; i = i * 2 + 1)
{
if (i + 1 < end && this.heap[i] < this.heap[i + 1]) i++
if (temp >= this.heap[i]) break
this.heap[sta] = this.heap[i]
sta = i
}
this.heap[sta] = temp
}
adjustMinHeap (sta, end)
{
let temp = this.heap[sta]
for (let i = 2 * sta + 1; i < end; i = i * 2 + 1)
{
if (i + 1 < end && this.heap[i] > this.heap[i + 1]) i++
if (temp <= this.heap[i]) break
this.heap[sta] = this.heap[i]
sta = i
}
this.heap[sta] = temp
}
createMaxHeap ()
{
for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--)
{
this.adjustMaxHeap(i, this.heap.length)
}
}
createMinHeap ()
{
for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--)
{
this.adjustMinHeap(i, this.heap.length)
}
}
}
module.exports = { Heap }
堆排序
代码请看内部排序里选择排序的堆排序
https://www.jianshu.com/p/16423d3e4fd9
网友评论