-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpriority_queue.js
61 lines (49 loc) · 1.74 KB
/
priority_queue.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() { // namespace
var exports = (typeof module !== 'undefined' && module.exports) ?
module.exports : window.priority_queue = {};
exports.PriorityQueue = function PriorityQueue(compare, queue) {
if (!(this instanceof PriorityQueue)) return new PriorityQueue(compare, queue);
compare = compare || min_first;
queue = queue || [];
function swap(i, j) { var t = queue[i]; queue[i] = queue[j]; queue[j] = t; }
function heapify(i) {
var length = queue.length, x, l, r;
while (true) {
x = i; l = left(i); r = right(i);
if (l < length && compare(queue[l], queue[x]) < 0) x = l;
if (r < length && compare(queue[r], queue[x]) < 0) x = r;
if (x === i) break;
swap(i, x);
i = x;
}
}
function remove(i) {
var t = queue[i], b = queue.pop();
if (queue.length > 0) {
queue[i] = b;
heapify(i);
}
return t;
}
this.push = function push(/* element, ... */) {
var i = queue.length, e = i + arguments.length, j, p;
queue.push.apply(queue, arguments);
for (; i < e; ++i) {
j = i; p = parent(i);
for (; j > 0 && compare(queue[j], queue[p]) < 0; j = p, p = parent(j)) {
swap(j, p);
}
}
return queue.length;
}
this.shift = function shift() { return remove(0); }
this.__defineGetter__('length', function length() { return queue.length });
for (var i = parent(queue.length - 1); i >= 0; --i) { heapify(i) }
}
function left(i) { return 2 * i + 1 }
function right(i) { return 2 * i + 2 }
function parent(i) { return Math.floor((i + 1) / 2) - 1 }
var max_first = exports.max_first = function max_first(a, b) { return b - a }
, min_first = exports.min_first = function min_first(a, b) { return a - b }
;
})(); // end of namespace