美文网首页js数据结构和算法
堆排序的堆类 --- Javascript实现

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

作者: mvlg | 来源:发表于2020-07-24 02:27 被阅读0次

    堆排序

    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实现

        本文链接:https://www.haomeiwen.com/subject/lcyrlktx.html