-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.ts
82 lines (64 loc) · 1.66 KB
/
heap.ts
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
/*
min [50, 60, 70, 90, 80, 100]
*/
export class Heap {
list: number[];
constructor() {
// block first element
this.list = [-1];
}
insert(val: number) {
// add data to end of heap
this.list.push(val);
// adjust its parent
let index = this.list.length - 1;
let parent = Math.trunc(index / 2);
while (index > 1 && this.list[index] < this.list[parent]) {
const temp = this.list[index];
this.list[index] = this.list[parent];
this.list[parent] = temp;
index = parent;
parent = Math.trunc(index / 2);
}
}
top(): number {
return this.list[1];
}
// remote the 1st index in the min heap
pop() {
// swap first and last element
// remote the last element
// fix the heap using heapify(1) => O (log N)
// swap
const last = this.list.length - 1;
const temp = this.top();
this.list[1] = last;
this.list[this.list.length - 1] = temp;
// remove the last element
this.list.pop();
// fix the heap
this.heapify(1);
}
heapify(index: number) {
const left = 2 * index;
const right = 2 * index + 1;
let minIndex = index;
// find the min of left right and node
if (left < this.list.length && this.list[left] < this.list[index]) {
minIndex = left;
}
if (right < this.list.length && this.list[right] < this.list[index]) {
minIndex = right;
}
if (minIndex !== index) {
//swap index and min index
const temp = this.list[index];
this.list[index] = this.list[minIndex];
this.list[minIndex] = temp;
this.heapify(minIndex);
}
}
isEmpty() {
return this.list.length < 2;
}
}