이진 트리 형태를 가지며 우선순위가 높은 요소가 먼저 나가기 위해 요소가 삽입, 삭제 될 때 바로 정렬되는 특징이 있다.
class MaxHeap {
constructor() {
this.heap = [null];
}
push(value) {
this.heap.push(value);
let currentIndex = this.heap.length - 1;
let parentIndex = Math.floor(currentIndex / 2);
while (parentIndex !== 0 && this.heap[parentIndex] < value) {
const temp = this.heap[parentIndex];
this.heap[parentIndex] = value;
this.heap[currentIndex] = temp;
currentIndex = parentIndex;
parentIndex = Math.floor(currentIndex / 2);
}
}
pop() {
const value = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIndex = 1;
let leftChild = currentIndex * 2;
let rightChild = currentIndex * 2 + 1;
while (this.heap[currentIndex] < this.heap[leftChild] ||
this.heap[currentIndex] < this.heap[rightChild]) {
const temp = this.heap[currentIndex];
if (this.heap[leftChild] < this.heap[rightChild]) {
this.heap[currentIndex] = this.heap[rightChild];
this.heap[rightChild] = temp;
currentIndex = rightChild;
} else {
this.heap[currentIndex] = this.heap[leftChild];
this.heap[leftChild] = temp;
currentIndex = leftChild;
}
leftChild = currentIndex * 2;
rightChild = currentIndex * 2 + 1;
}
return value;
}
}
class MinHeap {
constructor() {
this.heap = [null];
}
push(value) {
this.heap.push(value);
let currentIndex = this.heap.length - 1;
let parentIndex = Math.floor(currentIndex / 2);
while (parentIndex !== 0 && this.heap[parentIndex] > value) {
const temp = this.heap[parentIndex];
this.heap[parentIndex] = value;
this.heap[currentIndex] = temp;
currentIndex = parentIndex;
parentIndex = Math.floor(currentIndex / 2);
}
}
pop() {
const value = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIndex = 1;
let leftChild = currentIndex * 2;
let rightChild = currentIndex * 2 + 1;
while (this.heap[currentIndex] > this.heap[leftChild] ||
this.heap[currentIndex] > this.heap[rightChild]) {
const temp = this.heap[currentIndex];
if (this.heap[leftChild] > this.heap[rightChild]) {
this.heap[currentIndex] = this.heap[rightChild];
this.heap[rightChild] = temp;
currentIndex = rightChild;
} else {
this.heap[currentIndex] = this.heap[leftChild];
this.heap[leftChild] = temp;
currentIndex = leftChild;
}
leftChild = currentIndex * 2;
rightChild = currentIndex * 2 + 1;
}
return value;
}
}