-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
116 lines (92 loc) · 2.53 KB
/
main.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class MinHeap {
constructor(capacity, compare = (a, b) => a < b) {
this.tree = Array(capacity);
this.size = 0;
this.capacity = capacity;
this.compare = compare;
}
parent(i) {
return Math.floor((i - 1) / 2);
}
left(i) {
return 2 * i + 1;
}
right(i) {
return 2 * i + 2;
}
insertKey(k) {
this.size++;
if (this.size >= this.capacity) {
this.tree = this.tree.concat(Array(this.capacity));
this.capacity = this.tree.length;
}
this.tree[this.size - 1] = Number.POSITIVE_INFINITY;
this.decreaseKey(this.size - 1, k);
}
minHeapify(i) {
const l = 2 * i + 1;
const r = 2 * i + 2;
let smallest = i;
if (l < this.size && this.compare(this.tree[l] , this.tree[smallest])) {
smallest = l;
}
if (r < this.size && this.compare(this.tree[r] , this.tree[smallest])) {
smallest = r;
}
if (smallest != i)
{
this.swap(i, smallest);
this.minHeapify(smallest);
}
}
extractMin() {
if (this.size > 0) {
const min = this.tree[0];
this.tree[0] = this.tree[this.size - 1];
this.size--;
this.minHeapify(0);
return min;
} else throw "tree is empty";
}
decreaseKey(i, key) {
this.tree[i] = key;
while (i > 0 && this.compare(this.tree[i], this.tree[this.parent(i)])) {
this.swap(i, this.parent(i));
i = this.parent(i);
}
}
getMin() {
if (this.size > 0) {
return this.tree[0];
} else throw "tree is empty";
}
getNode(i) {
if (i < this.size) {
return this.tree[i];
} else throw "index out of bounds";
}
delete(i) {
this.decreaseKey(i, Number.NEGATIVE_INFINITY);
this.extractMin();
}
swap(i, j) {
const tmp = this.tree[i];
this.tree[i] = this.tree[j];
this.tree[j] = tmp;
}
display() {
console.log(this.tree.slice(0, this.size));
}
}
const arr = [9,8,7,6,5,4,3,2,1];
const minHeap = new MinHeap(arr.length);
for (const v of arr) {
minHeap.insertKey(v);
}
minHeap.display();
console.log(minHeap.extractMin());
minHeap.display();
console.log(minHeap.extractMin());
minHeap.display();
console.log(minHeap.extractMin());
minHeap.display();