우선순위 큐는 일반적인 FIFO인 큐와 달리 우선순위가 높은 요소가 먼저 나가는 개념이다.
힙은 우선순위 큐를 구현하기 위한 가장 적합한 방법이다.
우선순위 큐 !== 힙
class MaxHeap {
constructor() {
this.heap = [null];
}
insert(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);
}
}
}
const heap = new MaxHeap();
heap.insert(45);
heap.insert(36);
heap.insert(54);
heap.insert(27);
heap.insert(64);
console.log(heap.heap); // [null, 64, 54, 45, 27, 36]
class MaxHeap {
constructor() {
this.heap = [null];
}
remove() {
const returnValue = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIndex = 1;
let leftIndex = 2;
let rightIndex = 3;
while (
this.heap[currentIndex] < this.heap[leftIndex] ||
this.heap[currentIndex] < this.heap[rightIndex]
) {
if (this.heap[leftIndex] < this.heap[rightIndex]) {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[rightIndex];
this.heap[rightIndex] = temp;
currentIndex = rightIndex;
} else {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[leftIndex];
this.heap[leftIndex] = temp;
currentIndex = leftIndex;
}
leftIndex = currentIndex * 2;
rightIndex = currentIndex * 2 + 1;
}
return returnValue;
}
}
프로그래머스 데브코스 교육 내용을 바탕으로 정리한 글 입니다.