算法-堆实现js

  • 利用数组模拟堆结构
  • 堆的节点关系 i 的左节点 为 2i +1, 右节点 2i +2
i
2i+2
2i+1
  • 构造函数传入: data,compare,自由调整为最大堆和最小堆
	//最大堆
	let compare = (a,b) => a-b
    let heap = new Heap([],compare)
	//最小堆
	let compare = (a,b) => b-a
    let heap = new Heap([],compare)

使用案例

代码:

class Heap {

    constructor(data, compare) {
        this.list = [...data]
        this.compare = compare
    }
    // 获取数组
    getList() {
        return this.list
    }
    //返回数组大小
    size() {
        return this.list.length
    }
    //返回堆顶元素
    top() {
        if (!this.size()) return null
        return this.list[0]
    }
    //压入一个新的数据,并且开始向上调整节点
    push(i) {
        this.list.push(i)
        this.bubbleUp(this.list.length - 1)
    }
    //弹出一个数据,堆顶元素
    //如果数据不为空,将数组最后一个数据放入堆顶
    //开始向下调整
    pop() {
        if (!this.size()) return null
        let top = this.list[0]

        let tail = this.list.pop()
        if (this.size()) {
            this.list[0] = tail
            this.bubbleDown()
        }

        return top
    }
	//向上调整,如果节点 和 父节点 compare后,返回大于0,则相互交换
    bubbleUp(index) {
        let now = index
        let prev = (now - 1) >> 1
        while (now && this.compare(this.list[now], this.list[prev]) > 0) {
            this.swap(now, prev)
            now = prev
            prev = (now - 1) >> 1
        }
    }
    //向下调整,当前节点和其左右节点比较,和计较后最‘大’的节点交换
    bubbleDown() {
        let index = 0, lastIndex = this.size() - 1
        while (index < lastIndex) {
            let leftIndex = 2 * index + 1, rightIndex = 2 * index + 2
            let findIndex = index
            if (leftIndex <= lastIndex && this.compare(this.list[leftIndex], this.list[findIndex]) > 0) {
                findIndex = leftIndex
            }
            if (rightIndex <= lastIndex && this.compare(this.list[rightIndex], this.list[findIndex]) > 0) {
                findIndex = rightIndex
            }
            if (index !== findIndex) {
                this.swap(index, findIndex)
                index = findIndex
            } else {
                break
            }
        }
    }
    swap(i, j) {
        [this.list[i], this.list[j]] = [this.list[j], this.list[i]]
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值