본문 바로가기
알고리즘/복습

Priority Queue (우선순위 큐)

by 댕꼬 2022. 4. 7.

PriorityQueue


PriorityQueue란?

 

PriorityQueue란 우선순위 큐로써 일반적인 큐의 구조 FIFO(First In First Out)를 가지면서, 데이터가 들어온 순서대로 데이터가 나가는 것이 아니라 우선순위를 먼저 결정하고 그 우선순위가 높은 데이터가 먼저 나가는 자료구조이다.

 

PriorityQueue를 사용하기 위해서 우선순위 큐에 저장될 객체는 필수적으로 Comparable Interface를 구현해야한다.

Comparable Interface를 구현하면 compareTo method를 override 하게 되고 해당 객체에서 처리할 우선순위 조건을 리턴해주면 PriorityQueue 가 알아서 우선순위가 높은 객체를 추출 해준다.

 

우선순위를 반전시키는 방법은 객체 생성 시 Collections.reverseOrder()를 사용해 정렬 기준을 반전시킨다.

 

package day06.live;

import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueTest {

	public static void main(String[] args) {

		PriorityQueue<Integer> pQueue = new PriorityQueue<>();
		pQueue.offer(10);
		pQueue.offer(30);
		pQueue.offer(5);
		pQueue.offer(50);
		pQueue.offer(20);

		// 순서대로 정렬돼서 나옴 최소힙으로
		System.out.println(pQueue.poll());
		System.out.println(pQueue.poll());
		System.out.println(pQueue.poll());
		System.out.println(pQueue.poll());
		System.out.println(pQueue.poll());
		System.out.println("------------------------------");
		
		PriorityQueue<Integer> max = new PriorityQueue<>(Comparator.reverseOrder());
		max.offer(10);
		max.offer(30);
		max.offer(5);
		max.offer(50);
		max.offer(20);

		// 순서대로 정렬돼서 나옴 최소힙으로
		System.out.println(max.poll());
		System.out.println(max.poll());
		System.out.println(max.poll());
		System.out.println(max.poll());
		System.out.println(max.poll());
	}

}

위 코드의 출력 값

 

'알고리즘 > 복습' 카테고리의 다른 글

최장증가수열(LIS)  (0) 2022.04.06
Knapsack알고리즘  (0) 2022.04.05
[Java] Stack  (0) 2022.03.19
[Java] Queue  (0) 2022.03.19
[Java] 부분집합(Subset)  (0) 2022.03.15

댓글