Skip to content

Instantly share code, notes, and snippets.

@brianxautumn
Created April 16, 2017 07:00
Show Gist options
  • Save brianxautumn/ad6cd3cdaf4cc875566d33126a54e8f9 to your computer and use it in GitHub Desktop.
Save brianxautumn/ad6cd3cdaf4cc875566d33126a54e8f9 to your computer and use it in GitHub Desktop.
class MaxHeap{
constructor(){
this.data = [];
this.position = 1;
}
insert(value){
this.data[this.position] = value;
var bubbleCounter = this.position;
while(bubbleCounter > 1){
var parentIndex = ((bubbleCounter)/2 )|0;
if(this.data[bubbleCounter] > this.data[parentIndex]){
//swap
var temp = this.data[parentIndex];
this.data[parentIndex] = this.data[bubbleCounter];
this.data[bubbleCounter] = temp;
}
bubbleCounter = parentIndex;
}
this.position++;
}
}
var maxHeap = new MaxHeap();
maxHeap.insert(1);
maxHeap.insert(10);
maxHeap.insert(3);
maxHeap.insert(4);
maxHeap.insert(40);
maxHeap.insert(12);
console.log(maxHeap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment