Skip to content

Instantly share code, notes, and snippets.

@greathmaster
Last active July 20, 2020 00:31
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 greathmaster/fece77af4dfb934a61ee53c59d0deaab to your computer and use it in GitHub Desktop.
Save greathmaster/fece77af4dfb934a61ee53c59d0deaab to your computer and use it in GitHub Desktop.
Heap implementation in JS. Defaults to Min Heap. Inherit and override compare to implement a Max Heap
/*
Heap implementation in JS.
Description of Heap:
https://en.wikipedia.org/wiki/Heap_(data_structure)
Defaults to MinHeap. Extend class and override
compare(a, b) to implement MaxHeap.
*/
class Heap {
constructor() {
this.items = [];
}
leftChildIndex(parentIndex) {
return 2 * parentIndex + 1;
}
rightChildIndex(parentIndex) {
return 2 * parentIndex + 2;
}
parentIndex(childIndex) {
return Math.floor((childIndex - 1) / 2);
}
hasLeftChild(index) {
return this.leftChildIndex(index) < this.items.length;
}
hasRightChild(index) {
return this.rightChildIndex(index) < this.items.length;
}
hasParent(index) {
return this.parentIndex(index) >= 0;
}
leftChild(index) {
return this.items[this.leftChildIndex(index)];
}
rightChild(index) {
return this.items[this.rightChildIndex(index)];
}
parent(index) {
return this.items[this.parentIndex(index)];
}
swap(i1, i2) {
[this.items[i1], this.items[i2]] = [this.items[i2], this.items[i1]];
}
peak() {
if (this.items.length == 0) return null;
return this.items[0];
}
poll() {
if (this.items.length == 0) return null;
this.swap(0, this.items.length - 1);
let first = this.items.pop();
this.heapifyDown();
return first;
}
add(val) {
this.items.push(val);
this.heapifyUp();
}
heapifyUp() {
let i = this.items.length - 1;
while (this.hasParent(i) && this.compare(this.items[i], this.parent(i))) {
this.swap(this.parentIndex(i), i);
i = this.parentIndex(i);
}
}
heapifyDown() {
let i = 0;
while (this.hasLeftChild(i)) {
let smallChildIndex = this.leftChildIndex(i);
if (
this.hasRightChild(i) &&
this.compare(this.rightChild(i), this.leftChild(i))
) {
smallChildIndex = this.rightChildIndex(i);
}
if (this.compare(this.items[i], this.items[smallChildIndex])) {
break;
} else this.swap(i, smallChildIndex);
i = smallChildIndex;
}
}
print() {
console.log(this.items);
}
//Default to Min Heap
compare(a, b) {
return a <= b;
}
}
class MaxHeap extends Heap {
compare(a, b) {
return a >= b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment