前言:
在js中是没有堆这个数据结构的,但我们可以用类和Array模拟一个堆
实现步骤:
· 在类里,声明一个数组,用来装元素。
· 主要方法:插入、删除堆顶、获取堆顶、获取堆大小。
CODE:(以最小堆为例)
class MinHeap {
constructor() {
this.heap = []
}
swap(i1, i2) {
[this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]]
}
getParentIndex(i) {
return (i - 1) >> 1 // 相当于Math.floor((i - 1) / 2)