본문 바로가기

PL/JAVA

[JAVA] 우선순위 큐(Priority Queue), 오름차순(기본), 내림차순

사용하기
  • 우선순위 큐도 Java에서 내부적으로 구현되어 있어 사용이 용이하다.
  • 큐와 동일하게 add(), peek(), poll() 등의 메소드를 사용할 수 있다.

 

오름차순

  • add() 대신 offer() 메소드를 사용해도 동일한 결과를 얻는다.
우선순위 변경하기
  • 우선순위를 정하는 기준은 Java의 정렬 기준과 동일하다.
  • Java는 기본적으로 낮은 숫자부터 큰 숫자까지 오름차순으로 정렬하게 되는데, 만약 다른 오름차순으로 정렬하고 싶다면 Comparator 클래스나 Comparable 인터페이스를 이용해야 한다.
  • Ex) 객체의 어떤 값에 따라 우선순위를 정해 정렬해야 할때, 오름차순이 아닌 내림차순 정렬을 할때 등등
  • Integer는 Collections.reverseOrder()를 사용해 내림차순 정렬을 할 수 있다.

내림차순

정렬 기준 만들기

가끔 스트링의 문자열 중 2번째 자리로 정렬하거나, 이외의 특정 기준으로 정렬하고 싶을 때는 Comparator을 사용합니다.

 

 

 

 

[자바/java] 우선순위 큐 정렬하기 priorityQueue sort

Heap 구조에 대해서는 tosuccess.tistory.com/31?category=853902 를 참고해주세요! 우선순위 큐는 힙(Heap)구조를 가지며, 정렬 기준에 따라 가장 큰 값이 먼저 나오는 MaxHeap을 만들 수 있고, 가장 작은 값이..

tosuccess.tistory.com

 

첫 번째 방법은 새로운 클래스를 정의 하고 Comparable을 상속받아 오름차순의 기준을 직접 정의하는 것이다.

compareTo 함수를 오버라이딩 하여 재정의 하면 priorityQueue 를 바로 사용할 수 있다. 

class People implements Comparable<People>{
	String name;
	int bigThree1rm;

	People(String name, int bigThree1rm){
		this.name = name;
		this.bigThree1rm = bigThree1rm;
	}

	@Override //bigThree1rm 을 기준으로 오름차순 정렬
	public int compareTo(People o) {
		return this.bigThree1rm > o.bigThree1rm ? 1 : -1;
	}
}

PriorityQueue<People> priorityQueue = new PriorityQueue<People>();

 

두 번째 방법은 priorityQueue 를 정의 할 때 Comparator를 통해 compare 함수를 오버라이딩 하는 방법이다

static class People{
	String name;
	int bigThree1rm;

	People(String name, int bigThree1rm){
		this.name = name;
		this.bigThree1rm = bigThree1rm;
	}
}

PriorityQueue<People> priorityQueueAsc = new PriorityQueue<People>(new Comparator<People>() {
	@Override //bigThree1rm 을 기준으로 오름차순 정렬
	public int compare(People o1, People o2) {
		return o1.bigThree1rm > o2.bigThree1rm ? 1 : -1;
	}
});

 

 

JAVA Priority Queue 우선순위 큐 사용법과 정렬 기준 정의

기본적으로 Integer 값 혹은 String 같은 타입을 담는 우선순위 큐는 아래와 같은 방식으로 사용하면 된다. import java.util.*; // Priority_Queue 오름차순 정의 PriorityQueue priorityQueueAsc = new Priority..

eno1993.tistory.com

https://woovictory.github.io/2020/05/13/PriorityQueue/