Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Created September 4, 2016 16:52
Show Gist options
  • Save antoniopicone/114a994f990134d7eea3e572a70fe8fc to your computer and use it in GitHub Desktop.
Save antoniopicone/114a994f990134d7eea3e572a70fe8fc to your computer and use it in GitHub Desktop.
A JS implementation of a Heap. HeapSort function also provided.
var Heap = function(input) {
this.arrayLength = input.length ;
for(var j= Math.floor(this.arrayLength / 2);j>=0; j--) {
this.heapify(input,j);
console.log(j);
}
};
Heap.prototype.swap = function (array,a,b) {
var temp = array[a];
array[a] = array[b];
array[b] = temp;
};
Heap.prototype.heapify = function(input,i) {
var left = 2*i + 1;
var right = 2*i + 2;
var parent = i;
if(left < this.arrayLength && input[left] > input[parent] ) {
parent = left;
}
if(right < this.arrayLength && input[right] > input[parent] ) {
parent = right;
}
if(parent != i) {
this.swap(input,i,parent);
this.heapify(input,parent);
}
} ;
Heap.prototype.heapSort = function(input) {
for (var i=input.length - 1; i > 0; i--) {
this.swap(input,0,i);
this.arrayLength--;
this.heapify(input,0);
}
};
var input = [3,1,4,5,6,2];
var h = new Heap(input);
h.heapSort(input);
console.log(input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment