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
- 알고리즘 수업-깊이 우선 탐색1
- 백준 1068번 트리
- 2275번
- level0
- 리덕스
- 우선순위 큐 자바스크립트
- 자바스크립트
- 기지국 설치 js
- 1937번 욕심쟁이 판다
- 24480번
- 2638번 치즈
- 백준 2638번
- Java
- level1
- 백준 1068
- 프로그래머스
- 부녀회장이 될 테야
- 기지국 설치 자바스크립트
- JavaScript
- 백준 13023번
- ssh
- dfs
- 1389번 케빈 베이컨의 6단계 법칙
- 힙 자바스크립트
- React
- 13023번 ABCDE
- 1303번
- 알고리즘
- 백준
- Redux
Archives
- Today
- Total
코딩왕랄프👊🏻
자바스크립트로 우선순위 큐 구현하기 본문
반응형
SMALL
자바스크립트는 heap 을 따로 제공하지 않는다.
따라서 우선순위 큐를 사용하기 위해서는 직접 구현을 해야하는데, 다음과 같다.
class PriorityQueue {
constructor() {
this.heap = [];
}
getLeftChildIndex(parentIndex) {
return parentIndex * 2 + 1;
}
getRightChildIndex(parentIndex) {
return parentIndex * 2 + 2;
}
getParentIndex(childIndex) {
return Math.floor((childIndex - 1) / 2);
}
empty() {
return this.heap.length === 0;
}
peek() {
return this.heap[0];
}
push(data) {
this.heap.push(data);
this.heapifyUp();
}
// 최근에 삽입된 노드가 제 자리를 찾아갈 수 있도록 하는 메소드
heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = this.getParentIndex(index);
if (this.heap[parentIndex] > this.heap[index]) {
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
index = parentIndex;
} else break;
}
}
pop() {
const len = this.heap.length;
const rootNode = this.peek();
if (len <= 0) return;
if (len === 1) this.heap = [];
else {
this.heap[0] = this.heap.pop(); // 끝에 있는 노드를 루트노드로 변경
this.heapifyDown();
}
return rootNode;
}
// 변경된 루트노드가 제 자리를 찾아가도록 하는 메소드
heapifyDown() {
let index = 0;
const len = this.heap.length;
const rootNode = this.peek();
while (this.getLeftChildIndex(index) < len) {
const leftChildIndex = this.getLeftChildIndex(index);
const rightChildIndex = this.getRightChildIndex(index);
const smallerChildIndex = rightChildIndex < len && this.heap[rightChildIndex] < this.heap[leftChildIndex] ? rightChildIndex : leftChildIndex;
// 자식 노드의 키 값이 루트노드보다 작다면 위로 끌어올린다.
if (this.heap[smallerChildIndex] <= rootNode) {
[this.heap[index], this.heap[smallerChildIndex]] = [this.heap[smallerChildIndex], this.heap[index]];
index = smallerChildIndex;
} else break;
}
}
}
반응형
LIST
'Javascript' 카테고리의 다른 글
[Javascript] Array fill (0) | 2023.04.03 |
---|---|
[프로그래머스] 삼각형의 완성조건(1) Javascript (0) | 2023.02.07 |
[Javascript] 이벤트 처리기 (0) | 2022.09.21 |
[Javascript] String 객체, 메서드 (0) | 2022.09.21 |
[Javascript] Math 객체, 메서드 (0) | 2022.09.21 |