堆
- 利用数组模拟堆结构
- 堆的节点关系 i 的左节点 为 2i +1, 右节点 2i +2
- 构造函数传入: 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
}
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]]
}
}