
최대 힙(Max Heap)
최소 힙(Min Heap)
class MinHeap {
constructor() {
this.heap = [];
}
insert(val) {
this.heap.push(val);
this.bubbleUp();
}
bubbleUp() {
let idx = this.heap.length - 1;
while (idx > 0) {
let parentIdx = Math.floor((idx - 1) / 2);
if (this.heap[parentIdx] <= this.heap[idx]) break;
[this.heap[parentIdx], this.heap[idx]] = [this.heap[idx], this.heap[parentIdx]];
idx = parentIdx;
}
}
extractMin() {
if (this.heap.length === 0) return undefined;
const min = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this.sinkDown(0);
}
return min;
}
sinkDown(idx) {
const length = this.heap.length;
const element = this.heap[idx];
while (true) {
let leftIdx = 2 * idx + 1;
let rightIdx = 2 * idx + 2;
let swap = null;
if (leftIdx < length && this.heap[leftIdx] < element) {
swap = leftIdx;
}
if (rightIdx < length &&
this.heap[rightIdx] < (swap === null ? element : this.heap[leftIdx])) {
swap = rightIdx;
}
if (swap === null) break;
[this.heap[idx], this.heap[swap]] = [this.heap[swap], this.heap[idx]];
idx = swap;
}
}
}
import heapq
heap = []
heapq.heappush(heap, 4)
heapq.heappush(heap, 1)
heapq.heappush(heap, 7)
minimum = heapq.heappop(heap) # 최소값 1 반환, 힙에서 제거
최대힙을 구현할 경우에는 값을 음수로 바꿔서 넣는 방식으로 처리한다.
python
import heapq
heap = []
heapq.heappush(heap, -4)
heapq.heappush(heap, -1)
heapq.heappush(heap, -7)
maximum = -heapq.heappop(heap) # 최대값 7 반환, 힙에서 제거