-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityQueue.js
More file actions
65 lines (48 loc) · 1.16 KB
/
priorityQueue.js
File metadata and controls
65 lines (48 loc) · 1.16 KB
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
62
63
64
65
'use strict';
module.exports = PriorityQueue;
function PriorityQueue(){
this.queue = [];
}
PriorityQueue.prototype = {
push : function (priority, value) {
this._insert([priority, value], this.queue);
},
pop : function () {
return this.queue.pop()[1];
},
length : function () {
return this.queue.length;
},
peak : function() {
return this.queue[this.queue.length - 1];
},
_insert : function(value, array, startVal, endVal){
var length = array.length;
if (length == 0) {
array.push(value);
return;
}
var start = typeof(startVal) !== 'undefined' ? startVal : 0;
var end = typeof(endVal) !== 'undefined' ? endVal : length - 1;
var m = start + Math.floor((end - start)/2);
if (value[0] >= array[end][0]) {
array.splice(end + 1, 0, value);
return;
}
if (value[0] <= array[start][0]) {
array.splice(start, 0, value);
return;
}
if (start >= end) {
return;
}
if (value[0] < array[m][0]) {
this._insert(value, array, start, m - 1);
return;
}
if (value[0] > array[m][0]) {
this._insert(value, array, m + 1, end);
return;
}
},
}