Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Created October 21, 2017 12:30
Show Gist options
  • Save antoniopicone/8df8a97c4453a59cf576ed4f36ce029b to your computer and use it in GitHub Desktop.
Save antoniopicone/8df8a97c4453a59cf576ed4f36ce029b to your computer and use it in GitHub Desktop.
Array.prototype.swap = function(x,y) {
if(this[x] == undefined || this[y] == undefined) return;
var temp = this[x];
this[x] = this[y];
this[y] = temp;
};
var MaxHeapify = function(A,i) {
var l = 2*i;
var r = 2*i +1;
var largest = i;
if(l <= heap_size && A[l] > A[largest]) {
largest = l;
}
if(r <= heap_size && A[r] > A[largest]) {
largest = r;
}
if (largest != i) {
A.swap(i,largest);
MaxHeapify(A,largest);
}
};
var BuildMaxHeap = function(A) {
var middle = Math.floor(A.length / 2);
for(var i=middle; i>=1;i--) {
MaxHeapify(A,i);
}
};
var HeapSort = function(A) {
BuildMaxHeap(A);
for(var i=A.length;i>=2;i--) {
A.swap(1,i);
heap_size--;
MaxHeapify(A,1);
}
};
var arr = [null,4,8,1,3,2,15,9,10,14,8,7];
var heap_size = arr.length;
HeapSort(arr);
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment