자료구조 - 우선순위 큐(Priority Queue)

조성주·2023년 3월 25일
0

자료구조

목록 보기
6/12
post-thumbnail

❓ 우선순위 큐

  • 우선순위를 고려하여 먼저 넣은 데이터가 먼저 나오는 FIFO(First In First Out) 기반의 선형 자료 구조이다.
  • 우선순위 정렬 방식 : 배열 기반, 연결리스트 기반, 힙(Heap) 기반 등의 정렬 방식 존재

// Element() : 데이터와 우선순위를 지정하기 위한 생성자 함수
function Element(data, priority) {
  this.data = data; // 데이터
  this.priority = priority; // 우선순위
};

// PriorityQueue() : Element 관리를 위한 생성자 함수
function PriorityQueue() {
  this.array = [];
};

✏️ 구현 메서드(Method)

📗 getBuffer() : 객체 내 데이터 셋 반환

PriorityQueue.prototype.getBuffer = function () {
  return this.array.map((element) => element.data);
};

📗 isEmpty() : 객체 내 데이터 존재 여부 파악

PriorityQueue.prototype.isEmpty = function () {
  return this.array.length === 0;
};

📗 enqueue() : 데이터 추가

PriorityQueue.prototype.enqueue = function (data, priority) {
  let element = new Element(data, priority);
  let added = false;
  
  for(let i = 0; i < this.array.length; i++){
    if(element.priority < this.array[i].priority){
      this.array.splice(i, 0, element);
      added = true;
      break;
    }
  }
  
  if(!added){
    this.array.push(element);
  }
  
  return this.array.length;
};

📗 dequeue() : 데이터 삭제

PriorityQueue.prototype.dequeue = function() {
  return this.array.shift();
};

📗 front() : 가장 첫 데이터 반환

PriorityQueue.prototype.front = function() {
  return this.array.length === 0 ? undefined : this.array[0].data;
};

📗 size() : 우선순위 큐 데이터 개수 반환

PriorityQueue.prototype.size = function () {
  return this.array.length;
};

📗 clear() : 큐 초기화

PriorityQueue.prototype.clear = function () {
  return this.array = [];
};
profile
프론트엔드 개발자가 되기 위한 기록

0개의 댓글