-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathheap.js
61 lines (51 loc) · 1.42 KB
/
heap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
function Heap(comparer) {
if (typeof comparer !== 'function') throw new TypeError("comparer is not a function");
this.items = [];
this.length = 0;
this.comparer = comparer;
}
Heap.prototype.insert = function (x) {
var pos = this.length++;
if (pos >= this.items.length)
this.items.length *= 2;
var comparer = this.comparer;
var parent;
while (pos > 0 && comparer(x, this.items[parent = (pos - 1) >> 1]) < 0) {
this.items[pos] = this.items[parent];
pos = parent;
}
this.items[pos] = x;
};
Heap.prototype.pop = function () {
if (this.length == 0) return void 0;
var result = this.items[0];
if (this.length == 1) {
this.items[--this.length] = void 0;
return result;
}
var x = this.items[this.length - 1];
this.items[--this.length] = void 0;
var pos = 0, last = this.length - 1;
var comparer = this.comparer;
var next;
while ((next = 1 + pos + pos) < last) {
if (comparer(this.items[next], this.items[next + 1]) > 0) next++;
if (comparer(x, this.items[next]) < 0) break;
this.items[pos] = this.items[next];
pos = next;
}
if (1 + pos + pos == last && comparer(x, this.items[last]) > 0) {
this.items[pos] = this.items[last];
pos = last;
}
this.items[pos] = x;
return result;
}
Object.defineProperty(Heap.prototype, "top", {
get: function () { return this.items[0]; },
enumerable: false,
configurable: true,
});
module.exports = {
Heap: Heap,
};