-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (107 loc) ยท 2.76 KB
/
index.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
117
118
119
/**
* Heap
* ์ฐ์ ์์ ํ๋ฅผ ์ํ ์๋ฃ๊ตฌ์กฐ
* ์ฝ์
: O(log n)
* ์ญ์ : O(log n)
*/
class Heap {
constructor() {
this.heap = [null];
}
/**
* @description O(log n)์ ์๊ฐ ๋ณต์ก๋
* @param {number} data - ์ฝ์
ํ ๋ฐ์ดํฐ
*/
insert(data) {
if (this.heap.length <= 1) {
return void this.heap.push(data);
}
this.heap.push(data);
let index = this.heap.length - 1;
let parentIndex = Math.floor(index / 2);
// root๊ฐ ์๋๋ฉฐ ์์ ์ ๋ถ๋ชจ๋ณด๋ค ํด ๊ฒฝ์ฐ ์คํ
while (index > 1 && this.heap[parentIndex] < this.heap[index]) {
// ๋ถ๋ชจ์ ์์ ์ swap
[this.heap[parentIndex], this.heap[index]] = [
this.heap[index],
this.heap[parentIndex],
];
index = parentIndex;
parentIndex = Math.floor(index / 2);
}
}
/**
* @description O(log n)์ ์๊ฐ ๋ณต์ก๋
*/
delete() {
if (this.heap.length < 2) {
this.heap = [null];
return;
}
let index = 1;
this.heap[index] = this.heap.pop();
while (this.heap[index * 2] < this.heap.length) {
const leftChildIndex = index * 2;
const rightChildIndex = index * 2 + 1;
// ์ค๋ฅธ์ชฝ ์์์ด ์์ ๊ฒฝ์ฐ
if (rightChildIndex < this.heap.length - 1) {
// ์ผ์ชฝ, ์ค๋ฅธ์ชฝ ์์์ด ๋ชจ๋ ์์ ๋ณด๋ค ์์ ๊ฒฝ์ฐ break
if (
this.heap[index] > this.heap[leftChildIndex] &&
this.heap[index] > this.heap[rightChildIndex]
) {
break;
}
// ์ค๋ฅธ์ชฝ ์์์ด ์ผ์ชฝ ์์๋ณด๋ค ํฐ ๊ฒฝ์ฐ ์ค๋ฅธ์ชฝ ์์๊ณผ swap
if (this.heap[rightChildIndex] > this.heap[leftChildIndex]) {
[this.heap[rightChildIndex], this.heap[index]] = [
this.heap[index],
this.heap[rightChildIndex],
];
index = rightChildIndex;
}
// ์ผ์ชฝ ์์์ด ์ค๋ฅธ์ชฝ ์์๋ณด๋ค ํฐ ๊ฒฝ์ฐ ์ผ์ชฝ ์์๊ณผ swap
else {
[this.heap[leftChildIndex], this.heap[index]] = [
this.heap[index],
this.heap[leftChildIndex],
];
index = leftChildIndex;
}
}
// ์ค๋ฅธ์ชฝ ์์์ด ์์ ๊ฒฝ์ฐ
else {
// ์ผ์ชฝ ์์์ด ์์ ๋ณด๋ค ์์ ๊ฒฝ์ฐ
if (this.heap[index] > this.heap[leftChildIndex]) {
break;
}
[this.heap[leftChildIndex], this.heap[index]] = [
this.heap[index],
this.heap[leftChildIndex],
];
index = leftChildIndex;
}
}
}
}
const heap = new Heap();
heap.insert(1);
heap.insert(2);
heap.insert(3);
heap.insert(4);
heap.insert(5);
/**
* 5
* / \
* 4 2
* / \
* 1 3
*/
heap.delete();
heap.delete();
/**
* 3
* / \
* 1 2
*/
console.log(JSON.stringify(heap.heap));