Skip to content

Commit ce13ff2

Browse files
authored
Merge pull request mgechev#100 from krzysztof-grzybek/master
Fix heap
2 parents 0ecc151 + c822875 commit ce13ff2

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/data-structures/heap.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@
8282
}
8383

8484
if (right < this._heap.length &&
85-
this._cmp(this._heap[right], this._heap[index]) > 0) {
85+
this._cmp(this._heap[right], this._heap[index]) > 0 &&
86+
this._cmp(this._heap[right], this._heap[left]) > 0) {
8687
extr = right;
8788
}
8889

@@ -116,6 +117,7 @@
116117
index = parent;
117118
parent = Math.floor(parent / 2);
118119
}
120+
this._heapify(index);
119121
}
120122
return parent;
121123
};

test/data-structures/heap.spec.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,38 @@ describe('Heap', function () {
5858
res = heap.extract();
5959
expect(res).toBe(66);
6060
});
61+
it('should update top node properly', function () {
62+
var heap = new Heap(function (a, b) {
63+
return a.val - b.val;
64+
});
65+
var objectToUpdate = { val: 66 };
66+
heap.add(objectToUpdate);
67+
heap.add({ val: 11 });
68+
heap.add({ val: 55 });
69+
objectToUpdate.val = 0;
70+
heap.update(objectToUpdate);
71+
var res = heap.extract();
72+
expect(res.val).toBe(55);
73+
res = heap.extract();
74+
expect(res.val).toBe(11);
75+
res = heap.extract();
76+
expect(res.val).toBe(0);
77+
});
78+
it('should update bottom node properly', function () {
79+
var heap = new Heap(function (a, b) {
80+
return a.val - b.val;
81+
});
82+
var objectToUpdate = { val: 0 };
83+
heap.add(objectToUpdate);
84+
heap.add({ val: 11 });
85+
heap.add({ val: 55 });
86+
objectToUpdate.val = 66;
87+
heap.update(objectToUpdate);
88+
var res = heap.extract();
89+
expect(res.val).toBe(66);
90+
res = heap.extract();
91+
expect(res.val).toBe(55);
92+
res = heap.extract();
93+
expect(res.val).toBe(11);
94+
});
6195
});

0 commit comments

Comments
 (0)