Last active
June 27, 2021 03:39
-
-
Save linfongi/9ead2e09e2f1330624a0514242285dbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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