우선순위를 고려하여 먼저 넣은 데이터가 먼저 나오는 FIFO(First In First Out) 기반의 선형 자료 구조
배열 기반, 연결리스트 기반, 힙 기반 등의 정렬 방식 존재
비행기 탑승, 병원 응급실처럼 우선순위가 높은 쪽이 더 빠르게 진입하는 곳
function Element(data, priority) {
this.data = data;
this.priority = priority;
}
function PriorityQueue() {
this.array = [];
}
array 내부에 data와 priority를 저장한 객체가 담겨 있기 때문에 데이터만 반환하기 위해서는 map을 사용해서 element의 data를 저장해준다.
PriorityQueue.prototype.getBuffer = function() {
return this.array.map(element => element.data);
}
PriorityQueue.prototype.isEmpty = function() {
return this.array.length == 0;
}
PriorityQueue.prototype.enqueue = function(element, priority) {
let element = new Element(element, priority);
let added = false;
for (let i = 0; i < this.length; ++i) {
if (element.priority < this.array[i].priority) {
this.array.splice(i, 0, element);
added = true;
break;
}
}
if (!added) return this.array.push(element);
}
PriorityQueue.prototype.dequeue = function() {
return this.array.shift();
}
아래 3개의 메서드는 일반 queue와 동일
PriorityQueue.prototype.front = function() {
return this.array.length === 0 ? undefined : this.array[0].data;
}
PriorityQueue.prototype.size = function() {
return this.array.length;
}
PriorityQueue.prototype.clear = function() {
return this.array = [];
}
관련 전체 코드는 Git에 업로드 해두었습니다.
Github_PriorityQueue