堆排序的堆类 --- Javascript实现

堆排序

  1. 最大堆(儿子皆小于双亲)
  2. 最小堆(双亲皆小于儿子)

堆建立

  1. 构建堆调整函数(调整范围,索引以下的部分,至少包含子结点)
  2. 构建的位置是最后叶子节点的双亲
  3. 最后叶子的双亲计算 (len / 2)- 1
  4. 从后往前,从下往上,确保最小堆的最小值的精准性,保证扫描范围的全面性。

堆取值

  1. 取值后会产生缺值的现象:(1)填值(2)重构
  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

你可能感兴趣的:(堆排序的堆类 --- Javascript实现)