-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityQueue.ts
More file actions
75 lines (62 loc) · 1.99 KB
/
Copy pathpriorityQueue.ts
File metadata and controls
75 lines (62 loc) · 1.99 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
66
67
68
69
70
71
72
73
74
import { heap, iHeap } from '../heap/heap';
class PriorityNode<T> {
constructor(
public priority: number,
public value: T
) { }
}
type queue<T> = Array<PriorityNode<T>>;
class PriorityQueue<T> implements iHeap<T> {
private heap: queue<T> = new Array();
public getLeftChild = (index: number) => index * 2 + 1;
public getRightChild = (index: number) => index * 2 + 2;
public getParent = (index: number) => Math.floor((index - 1) / 2);
public peek = () => this.heap[0];
public insert(priority: number, item: T): PriorityNode<T> {
let node = new PriorityNode(priority, item);
this.heap.push(node);
let index = this.heap.length - 1;
while (index > 0) {
let parentIndex = this.getParent(index);
let parentNode = this.heap[parentIndex];
let currentNode = this.heap[index];
if (currentNode.priority > parentNode.priority) {
this.swap(index, parentIndex);
index = parentIndex
} else break;
}
return node;
}
public extractMax() {
const root = this.heap.shift();
this.heap.unshift(this.heap[this.heap.length - 1]);
this.heap.pop();
this.heapify(0);
return root;
}
public heapify(index: number) {
let left = this.getLeftChild(index);
let right = this.getRightChild(index);
let length = this.heap.length;
let smallest = index;
if (left < length && this.heap[smallest].priority < this.heap[left].priority) {
smallest = left;
}
if (right < length && this.heap[smallest].priority < this.heap[right].priority) {
smallest = right;
}
if (smallest != index) {
this.swap(smallest, index);
this.heapify(smallest);
}
}
public swap(a: number, b: number): void {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]]
}
}
const priorityQueue = new PriorityQueue<number>();
priorityQueue.insert(33, 3);
priorityQueue.insert(4, 4);
priorityQueue.insert(31, 31);
priorityQueue.insert(6, 6);
console.log(`ExtractMax ${priorityQueue.extractMax()}`);