-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxHeap.ts
92 lines (80 loc) · 2.96 KB
/
MaxHeap.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
83
84
85
86
87
88
89
90
91
import { swap } from "helpers";
class MaxHeap {
values = []
add(val) {
this.values.push(val);
var currentIndex = this.values.length - 1;
var parentIndex = Math.floor((currentIndex - 1) / 2)
while (currentIndex > 0 && this.values[parentIndex] < this.values[currentIndex]) {
[this.values[parentIndex], this.values[currentIndex]] = [this.values[currentIndex], this.values[parentIndex]]
currentIndex = parentIndex;
parentIndex = Math.floor((currentIndex - 1) / 2);
}
}
extract() {
var lastIndex = this.values.length - 1;
swap({
array: this.values,
firstIndex: 0,
secondIndex: lastIndex
});
var removedElement = this.values.pop();
var currentPosition = 0;
var leftIndex = currentPosition * 2 + 1;
var rightIndex = currentPosition * 2 + 2;
while (currentPosition != lastIndex ||
(
this.values[currentPosition] < this.values[leftIndex]
||
this.values[currentPosition] < this.values[rightIndex]
)) {
if (this.values[currentPosition] < this.values[leftIndex]
&&
this.values[currentPosition] < this.values[rightIndex]) {
if (this.values[leftIndex] < this.values[rightIndex]) {
swap({
array: this.values,
firstIndex: rightIndex,
secondIndex: currentPosition
})
currentPosition = rightIndex;
}
else {
swap({
array: this.values,
firstIndex: leftIndex,
secondIndex: currentPosition
})
currentPosition = leftIndex;
}
} else {
if (this.values[currentPosition] < this.values[leftIndex]) {
swap({
array: this.values,
firstIndex: currentPosition,
secondIndex: leftIndex
});
currentPosition = leftIndex;
} else {
if (this.values[currentPosition] < this.values[rightIndex])
swap(
{
array: this.values,
firstIndex: currentPosition,
secondIndex: rightIndex
})
currentPosition = rightIndex;
}
}
leftIndex = currentPosition * 2 + 1;
rightIndex = currentPosition * 2 + 2;
}
}
}
var maxHeap = new MaxHeap();
var maxHeap = new MaxHeap();
var input = [43, 93, 11, 11, 33, 87, 47, 8]
for (let item of input) {
maxHeap.add(item)
}
console.log(maxHeap.values)