Skip to content

Instantly share code, notes, and snippets.

@brianxautumn
Created April 20, 2017 03:06
Show Gist options
  • Save brianxautumn/749de33cf63c8989f65687c8aab4e4fb to your computer and use it in GitHub Desktop.
Save brianxautumn/749de33cf63c8989f65687c8aab4e4fb to your computer and use it in GitHub Desktop.
//children are 2n + 1, 2
//parents are floor((n-1)/2)
class MaxHeap {
constructor() {
this.data = new Array(10);
this.size = 0;
}
insert(value) {
this.data[this.size] = value;
var current = this.size;
var parent;
var temp;
while (current > 0) {
parent = Math.floor((current - 1) / 2);
if (this.data[current] > this.data[parent]) {
temp = this.data[current];
this.data[current] = this.data[parent];
this.data[parent] = temp;
}
current = parent;
}
this.size++;
}
remove() {
if (this.size === 0)
return;
this.size--;
var current = 0;
var value = this.data[0];
this.swap(0, this.size);
while (current < this.size) {
var left_pointer = 2 * current + 1;
var right_pointer = 2 * current + 2;
var has_right = (right_pointer < this.size) ? true : false;
var has_left = (left_pointer < this.size) ? true : false;
if (!has_left) {
break;
}
//2 children
if (has_left && has_right) {
//check left vs right
if (this.checkGreater(left_pointer, right_pointer)) {
if (this.data[left_pointer] > this.data[current]) {
this.swap(left_pointer, current);
current = left_pointer;
}else{
break;
}
} else {
if (this.checkGreater(right_pointer, current)) {
this.swap(right_pointer, current);
current = right_pointer;
}else{
break;
}
}
} else {
//only check left
if (this.checkGreater(left_pointer, current)) {
this.swap(left_pointer, current);
current = left_pointer;
}else{
break;
}
}
}
return value;
}
swap(a, b) {
var temp;
temp = this.data[a];
this.data[a] = this.data[b];
this.data[b] = temp;
}
checkGreater(a, b){
return (this.data[a] > this.data[b]);
}
}
var maxHeap = new MaxHeap();
maxHeap.insert(10);
maxHeap.insert(0);
maxHeap.insert(3);
maxHeap.insert(4);
maxHeap.insert(20);
maxHeap.insert(-100);
maxHeap.insert(80);
console.log(maxHeap);
console.log(maxHeap.remove());
console.log(maxHeap.remove());
console.log(maxHeap.remove());
console.log(maxHeap.remove());
console.log(maxHeap.remove());
console.log(maxHeap.remove());
console.log(maxHeap.remove());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment