Skip to content

Instantly share code, notes, and snippets.

@aibolik
Created August 3, 2021 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aibolik/15c3aa7b6a5cff8834acbc986ceae58e to your computer and use it in GitHub Desktop.
Save aibolik/15c3aa7b6a5cff8834acbc986ceae58e to your computer and use it in GitHub Desktop.
Min Heap
class MinHeap {
constructor() {
this.arr = [];
}
insert(x) {
this.arr.push(x);
this.bubbleUp(this.arr.length - 1);
}
pop() {
const min = this.arr[0];
[this.arr[0], this.arr[this.arr.length - 1]] = [this.arr[this.arr.length - 1], this.arr[0]];
this.arr.pop();
this.bubbleDown(0);
return min;
}
left(node) {
return node * 2 + 1;
}
right(node) {
return node * 2 + 2;
}
parent(node) {
return Math.floor((node - 1) / 2);
}
bubbleDown(node) {
let min = node;
if (this.arr[this.left(node)] < this.arr[node]) {
min = this.left(node);
}
if (this.arr[this.right(node)] < this.arr[node]) {
min = this.right(node);
}
if (min !== node) {
[this.arr[node], this.arr[min]] = [this.arr[min], this.arr[node]];
this.bubbleDown(min);
}
}
bubbleUp(node) {
if (this.parent(node) >= 0 && this.arr[this.parent(node)] > this.arr[node]) {
[this.arr[this.parent(node)], this.arr[node]] = [this.arr[node], this.arr[this.parent(node)]];
this.bubbleUp(this.parent(node));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment