Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- DFS기초
- socket.io
- 파이썬
- react-query
- JS
- 재귀
- 코테
- 코딩테스트실력진단
- CSS
- 백준
- Express
- 블챌
- 코딩테스트
- 그리디알고리즘
- react
- django
- 완전탐색
- 백준알고리즘
- 자료구조
- 코드트리
- 그리디
- 스택자료구조
- DFS
- 구현
- 알고리즘
- DFS활용
- BFS
- 스택
- 문자열
- DP
Archives
- Today
- Total
꾸준하게 거북이처럼
Javascript - 최소힙 구현하기 본문
class MinHeap {
constructor() {
this.heap = [];
}
size() {
return this.heap.length;
}
swap(idx1, idx2) {
[this.heap[idx1], this.heap[idx2]] = [this.heap[idx2], this.heap[idx1]];
}
add(value) {// 값 추가
this.heap.push(value);
this.bubbleUp();
}
remove() {// Pop
if (this.heap.length === 1) {
return this.heap.pop();
}
const value = this.heap[0];
this.heap[0] = this.heap.pop();
this.bubbleDown();
return value;
}
bubbleUp() {
let index = this.heap.length - 1;
let parentIdx = Math.floor((index - 1) / 2);
while (
this.heap[parentIdx] &&
this.heap[index] < this.heap[parentIdx]
) {
this.swap(index, parentIdx);
index = parentIdx;
parentIdx = Math.floor((index - 1) / 2);
}
}
bubbleDown() {
let index = 0;
let leftIdx = index * 2 + 1;
let rightIdx = index * 2 + 2;
while (
(this.heap[leftIdx] && this.heap[leftIdx] < this.heap[index]) ||
(this.heap[rightIdx] && this.heap[rightIdx] < this.heap[index])
) {
let smallerIdx = leftIdx;
if (
this.heap[rightIdx] &&
this.heap[rightIdx] < this.heap[smallerIdx]
) {
smallerIdx = rightIdx;
}
this.swap(index, smallerIdx);
index = smallerIdx;
leftIdx = index * 2 + 1;
rightIdx = index * 2 + 2;
}
}
}
'Computer Science > 자료구조' 카테고리의 다른 글
Javascript - Queue 구현하기 (0) | 2024.05.22 |
---|---|
배열과 연결 리스트의 차이 (0) | 2023.02.26 |
백준 1918번 후위표기식 - 파이썬 (0) | 2022.07.19 |
백준 17298번 - 파이썬 (0) | 2022.07.16 |
백준 10799번 쇠막대기 - 파이썬 (0) | 2022.07.15 |
Comments