Skip to content

Instantly share code, notes, and snippets.

@linfongi
Last active June 27, 2021 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save linfongi/9ead2e09e2f1330624a0514242285dbc to your computer and use it in GitHub Desktop.
Save linfongi/9ead2e09e2f1330624a0514242285dbc to your computer and use it in GitHub Desktop.
function Heap(compare = (a, b) => a - b) {
const arr = [];
return { push, pop, peek, size };
function size() {
return arr.length;
}
function push(v) {
arr.push(v);
bubble();
}
function pop() {
const top = peek();
const last = arr.pop();
if (arr.length > 0) {
arr[0] = last;
sink();
}
return top;
}
function peek() {
return arr[0];
}
function bubble() {
let i = arr.length - 1;
let p = (i - 1) >> 1;
while (i !== 0 && compare(arr[i], arr[p]) < 0) {
[arr[i], arr[p]] = [arr[p], arr[i]];
i = p;
p = (i - 1) >> 1;
}
}
function sink() {
let i = 0;
for (;;) {
let next = i;
for (const childIdx of [i * 2 + 1, i * 2 + 2]) {
if (childIdx < arr.length && compare(arr[childIdx], arr[next]) < 0) {
next = childIdx;
}
}
if (next === i) return;
[arr[i], arr[next]] = [arr[next], arr[i]];
i = next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment