Skip to content

Instantly share code, notes, and snippets.

@gys-dev
Created January 16, 2026 15:26
Show Gist options
  • Select an option

  • Save gys-dev/1bdf34baece5a3d2f96685045ad68fc6 to your computer and use it in GitHub Desktop.

Select an option

Save gys-dev/1bdf34baece5a3d2f96685045ad68fc6 to your computer and use it in GitHub Desktop.
Heap
function heapify(tree, n, i) {
let min = i;
let l = 2 * i + 1;
let r = 2 * i + 2;
if (l < n && tree[l] < tree[min]) {
min = l;
}
if (r < n && tree[r] < tree[min]) {
min = r;
}
if (min !== i) {
[tree[i], tree[min]] = [tree[min], tree[i]];
heapify(tree, n, min);
}
}
function buildHeap(tree) {
let n = tree.length;
let startIdx = Math.floor(n / 2) - 1;
for (let i = startIdx; i >= 0; i--) {
heapify(tree, n, i);
}
}
function addHeap(tree, newItem) {
tree.push(newItem);
let idx = tree.length - 1;
while (idx > 0) {
let parentIdx = Math.floor((idx - 1) / 2);
if (tree[idx] >= tree[parentIdx]) break;
[tree[idx], tree[parentIdx]] = [tree[parentIdx], tree[idx]];
idx = parentIdx;
}
}
function deleteHeap(tree, idx = 0) {
if (tree.length === 0) return;
tree[idx] = tree[tree.length - 1];
tree.pop();
heapify(tree, tree.length, idx);
}
// ================= TEST =================
let aTree = [10, 7, 6, 1, 4, 3, 9, 0, 15];
console.log("origin:", aTree);
buildHeap(aTree);
console.log("heap:", aTree);
console.log("add -2");
addHeap(aTree, -2);
console.log(aTree);
console.log("delete min");
deleteHeap(aTree);
console.log(aTree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment