Skip to content

Commit

Permalink
minor refactor of bubbledown, 1.0.4
Browse files Browse the repository at this point in the history
  • Loading branch information
Andras committed Jan 4, 2015
1 parent e30232d commit cda0e4f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
26 changes: 15 additions & 11 deletions lib/qheap.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,33 +69,37 @@ Heap.prototype.remove = function Heap_remove( ) {
else {
var list = this._list;
var idx = 1;
var vi = list[len];
var item = list[len];

list[len] = undefined;
this.length = (len -= 1);

// bubble value down to reestablish partial ordering
// removing the root item left a hole. We will put the last item
// in the array into that hole, but first we bubble down the hole to a
// position where the left/right children will be in correct order.
var comparfn = this._comparFunc;
while (true) {
var l = 2 * idx, r = 2 * idx + 1;
var vl = list[l], vr = list[r];
if (r <= len && comparfn(vr, vi) < 0) {
if (comparfn(vl, vr) < 0) {
list[idx] = vl;
if (r <= len && comparfn(list[r], item) < 0) {
if (comparfn(list[l], list[r]) < 0) {
// left child comes before item or right child, move hole down
list[idx] = list[l];
idx = l;
}
else {
list[idx] = vr;
// right child comes before item, move hole down
list[idx] = list[r];
idx = r;
}
}
else if (l <= len && comparfn(vl, vi) < 0) {
var vl = list[l];
list[idx] = vl;
else if (l <= len && comparfn(list[l], item) < 0) {
// left child comes before item, move hole down
list[idx] = list[l];
idx = l;
}
else {
list[idx] = vi;
// item comes before either child of this hole, leave item here
list[idx] = item;
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "qheap",
"version": "1.0.3",
"version": "1.0.4",
"description": "binary heap priority queue",
"license": "Apache-2.0",
"repository": {
Expand Down

0 comments on commit cda0e4f

Please sign in to comment.