Skip to content

Instantly share code, notes, and snippets.

@Sammons
Last active August 29, 2015 14:00
Show Gist options
  • Save Sammons/11243071 to your computer and use it in GitHub Desktop.
Save Sammons/11243071 to your computer and use it in GitHub Desktop.
Javascript Heap
//takes an array, and a comparator for its elements
// e.g. function(a,b) {return a > b}
var heap = function(ary, comp) {
this.array = [];
this.comparator = comp;
this._swap = function(a,b) {
var tmp = this.array[a];
this.array[a] = this.array[b];
this.array[b] = tmp
}
this.extract_root = function() {
var a = this.array
var cmp = this.comparator
this._swap( 0, a.length -1 )
var root = a.pop()
var current_index = 0
var lchild_index = ( current_index * 2 ) + 1
var rchild_index = lchild_index + 1
while (!cmp( a[current_index], a[lchild_index] )
|| !cmp( a[current_index], a[rchild_index] )) {
if ( cmp ( a[rchild_index], a[lchild_index] )
&& rchild_index <= a.length ) {
this._swap( current_index, rchild_index )
current_index = rchild_index
} else if ( lchild_index < a.length ){
this._swap( current_index, lchild_index )
current_index = lchild_index
} else {
break;
}
lchild_index = ( current_index * 2 ) + 1
rchild_index = lchild_index + 1
}
return root
}
this.insert = function(element) {
this.array.push(element)
var a = this.array
var cmp = this.comparator
if (this.array.length == 1) return this
var current_index = a.length - 1
var parent_index = Math.floor( ( current_index - 1 ) / 2 )
while ( !cmp( a[ parent_index ], a[ current_index ] ) ) {
this._swap( current_index, parent_index )
current_index = parent_index
if (current_index == 0) return this
parent_index = Math.floor( ( current_index - 1 ) / 2 )
}
}
this.getShallowCopy = function(comp) {
if (comp) return new heap(this.array, comp);
return new heap(this.array, this.comparator);
}
this.getSortedArray = function() {
var me = this.getShallowCopy();
var array = [];
while (me.count > 0) array.push(me.extract_root());
return array;
}
for (var i in ary) this.insert(ary[i])
return this;
}
var a = []
for (var i = 0; i < 1000; i++) a.push(Math.round(Math.random()*1000))
// a = [12,3,4]
var h = new heap(a,function(a,b){return a>b;})
var prev = h.extract_root()
for (var i = 0; i < a.length -1; i++) {
var cur = h.extract_root()
console.log(cur)
if (cur > prev) return console.log('fail')
prev = cur
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment