Skip to content

Instantly share code, notes, and snippets.

@bepyan
Created August 19, 2021 09:17
Show Gist options
  • Save bepyan/07dec920c1ec5944d4da09f074d76aa1 to your computer and use it in GitHub Desktop.
Save bepyan/07dec920c1ec5944d4da09f074d76aa1 to your computer and use it in GitHub Desktop.
알고리즘 문제 풀이용 우선순위 큐
/**
* @arr 초기 배열
* @compare 객체에 대한 비교 함수
*/
const PQ = (arr, compare = (a, b) => a > b) => {
const heap = [];
const getPIdx = (i) => Math.floor((i - 1) / 2);
const getLIdx = (i) => i * 2 + 1;
const getRIdx = (i) => i * 2 + 2;
const swap = (a, b) => ([heap[a], heap[b]] = [heap[b], heap[a]]);
const isEmpty = () => !heap.length;
const enqueue = (v) => {
heap.push(v);
let i = heap.length - 1;
let p = getPIdx(i);
while (p >= 0 && compare(heap[p], heap[i])) {
swap(i, p);
i = p;
p = getPIdx(i);
}
};
const dequeue = () => {
if (!heap.length) return undefined;
if (heap.length === 1) return heap.pop();
const target = heap[0];
heap[0] = heap.pop();
let i = 0;
const len = heap.length;
while (getLIdx(i) < len) {
const l = getLIdx(i);
const r = getRIdx(i);
const minChildIdx = r < len && compare(heap[l], heap[r]) ? r : l;
if (compare(heap[minChildIdx], heap[i])) break;
swap(i, minChildIdx);
i = minChildIdx;
}
return target;
};
arr.forEach((v) => enqueue(v));
return { heap, isEmpty, enqueue, dequeue };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment