-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpriority-queue-linear-time.js
61 lines (46 loc) · 1.25 KB
/
priority-queue-linear-time.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
const insert = (array, index, element) => {
let runner = array.length - 1;
while (runner >= index) {
array[runner + 1] = array[runner];
runner--;
}
array[index] = element;
}
const priorityQueue = (array, element, start, end) => {
start = start || 0;
end = end || array.length - 1;
if (start > end) {
insert(array, end + 1, element);
return;
}
const mid = Math.floor(start + (end - start) / 2);
const midElement = array[mid];
if (element >= midElement) {
if (element < array[mid - 1]) {
insert(array, mid, element);
return;
}
return priorityQueue(array, element, start, mid - 1);
}
if (element < midElement) {
if (element >= array[mid + 1]) {
insert(array, mid + 1, element);
return;
}
return priorityQueue(array, element, mid + 1, end);
}
}
const priorityQueueWithLinearSearch = (array, element) => {
let i = array.length - 1;
while (element >= array[i]) {
i--;
}
insert(array, i + 1, element)
}
const array = [];
priorityQueue(array, 4);
priorityQueue(array, 8);
priorityQueue(array, 1);
priorityQueue(array, 7);
priorityQueue(array, 3);
console.log(array);