Last active
July 30, 2022 13:21
-
-
Save aarvay/22c6b32b8feff0d646fc3b2f00ef596d to your computer and use it in GitHub Desktop.
A small heap implementation
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(data = [], compare = (a, b) => a < b) { | |
const heap = [null]; | |
const size = () => heap.length - 1; | |
const leftIdx = (i) => i * 2 | |
const rightIdx = (i) => i * 2 + 1 | |
const parentIdx = (i) => Math.floor(i / 2); | |
const left = (i) => heap[leftIdx(i)]; | |
const right = (i) => heap[rightIdx(i)]; | |
const parent = (i) => heap[parentIdx(i)]; | |
const childIdx = (i) => { | |
if (!right(i)) return leftIdx(i); | |
return compare(left(i), right(i)) ? leftIdx(i) : rightIdx(i) | |
} | |
const child = (i) => heap[childIdx(i)] | |
const swapWithParent = (i) => { | |
const idx = parentIdx(i); | |
[heap[i], heap[idx]] = [heap[idx], heap[i]] | |
return idx; | |
} | |
const swapWithChild = (i) => { | |
const idx = childIdx(i); | |
swapWithParent(idx); | |
return idx; | |
} | |
const push = (val) => { | |
heap.push(val); | |
let idx = size(); | |
while (idx >= 2 && compare(heap[idx], parent(idx))) | |
idx = swapWithParent(idx); | |
} | |
const pop = () => { | |
const val = heap[1]; | |
heap[1] = heap[size()] | |
heap.length-- | |
let idx = 1; | |
while (left(idx) && compare(child(idx), heap[idx])) | |
idx = swapWithChild(idx); | |
return val | |
} | |
const peek = () => heap[1] | |
for (let i = 0; i < data.length; i++) | |
push(data[i]) | |
return { push, pop, peek, size } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment