JS实现最小堆
插入元素insert
- 将值插入堆的底部(数组的尾部)
- 执行上移操作:将这个值和父节点进行比较,直到父节点小于等于这个节点
- 大小为k的堆的插入元素的时间复杂度是O(logk)
删除堆顶pop
- 用数组尾部元素替换堆顶(直接删除堆顶会破坏堆的结构)
- 执行下移操作:堆顶元素和子节点进行比较,直至子节点大于等于新堆顶元素
- 大小为k的堆的删除堆顶的时间复杂度是O(logk)
获取堆顶peek
获取堆的长度size
class MinHeap {
constructor() {
this.heap = [];
}
swap(i1, i2) {
const temp = this.heap[i1];
this.heap[i1] = this.heap[i2];
this.heap[i2] = temp;
}
getParentIndex(index) {
return Math.floor((index - 1) / 2);
}
getLeftIndex(index) {
return index * 2 + 1;
}
getRightIndex(index) {
return index * 2 + 2;
}
shiftUp(index) {
if (index === 0) return
const parentIndex = this.getParentIndex(index);
if (this.heap[parentIndex] > this.heap[index]) {
this.swap(index, parentIndex);
this.shiftUp(parentIndex)
}
}
shiftDown(index) {
if (index === this.heap.length - 1) return;
const leftIndex = this.getLeftIndex(index);
const rightIndex = this.getRightIndex(index);
if (this.heap[index] > this.heap[leftIndex]) {
this.swap(index, leftIndex);
this.shiftDown(leftIndex);
}
if (this.heap[index] > this.heap[rightIndex]) {
this.swap(index, rightIndex);
this.shiftDown(rightIndex);
}
}
insert(val) {
this.heap.push(val);
this.shiftUp(this.heap.length - 1);
}
pop() {
this.heap[0] = this.heap.pop();
this.shiftDown(0);
}
peek() {
return this.heap[0];
}
size() {
return this.heap.length;
}
}
const heap = new MinHeap();
// 添加顺序不同,生成的堆也不同
heap.insert(5)
heap.insert(4)
heap.insert(3)
heap.insert(2)
heap.insert(1)
heap.pop()
// heap.insert(1)
// heap.insert(2)
// heap.insert(3)
// heap.insert(4)
// heap.insert(5)
// heap.pop()
打开App,阅读手记