## 최소 힙 ```javascript class MinHeap { constructor() { this.items = []; } size() { return this.items.length; } insert(item) { this.push(item); this.#bubbleUp(); } pop() { if (this.size() === 0) { return null; } const min = this.items[0]; this.items[0] = this.items[this.size() - 1]; this.items.pop(); this.#bubbleDown(); return min; } #swap(a, b) { [this.items[a], this.items[b]] = [this.items[b], this.items[a]]; } #bubbleUp() { let idx = this.size() - 1; while (idx > 0) { const parentIdx = Math.floor((idx - 1) / 2); if (this.items[parentIdx][0] <= this.items[idx][0]) { break; } this.#swap(idx, parentIdx); idx = parentIdx; } } #bubbleDown() { let idx = 0; while (idx * 2 + 1 < this.size()) { const leftChild = idx * 2 + 1; const rightChild = idx * 2 + 2; const smallerChild = rightChild < this.size() && this.items[rightChild][0] < this.items[leftChild][0] ? rightChild : leftChild; if (this.items[idx][0] <= this.items[smallerChild][0]) { break; } this.#swap(idx, smallerChild); idx = smallerChild; } } } ``` ## 최대 힙