高效管理优先级数据的核心结构
堆(Heap)是一种特殊的完全二叉树,满足堆性质:
insert(value):插入新元素,时间复杂度 O(log n)extractMax() / extractMin():取出并删除堆顶元素,时间复杂度 O(log n)peek():查看堆顶元素,时间复杂度 O(1)buildHeap(array):从数组构建堆,时间复杂度 O(n)class MinHeap {
constructor() {
this.heap = [];
}
getParentIndex(i) { return Math.floor((i - 1) / 2); }
getLeftChildIndex(i) { return 2 * i + 1; }
getRightChildIndex(i) { return 2 * i + 2; }
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
peek() {
return this.heap[0];
}
insert(value) {
this.heap.push(value);
this.heapifyUp();
}
heapifyUp() {
let index = this.heap.length - 1;
while (index > 0 && this.heap[this.getParentIndex(index)] > this.heap[index]) {
this.swap(index, this.getParentIndex(index));
index = this.getParentIndex(index);
}
}
extractMin() {
if (this.heap.length === 0) return null;
if (this.heap.length === 1) return this.heap.pop();
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown();
return min;
}
heapifyDown() {
let index = 0;
while (this.getLeftChildIndex(index) < this.heap.length) {
let smallerChildIndex = this.getLeftChildIndex(index);
if (this.getRightChildIndex(index) < this.heap.length &&
this.heap[this.getRightChildIndex(index)] < this.heap[smallerChildIndex]) {
smallerChildIndex = this.getRightChildIndex(index);
}
if (this.heap[index] < this.heap[smallerChildIndex]) break;
this.swap(index, smallerChildIndex);
index = smallerChildIndex;
}
}
}
点击下方按钮体验最小堆的操作: