자료구조 & 알고리즘/우선순위큐

우선순위 큐 예시 코드 (자바 우선순위 큐 사용 예시 - Comparable VS Comparator)

꾸준함의 미더덕 2024. 1. 16. 21:58

# Comparable 혹은 Comparator에서 

ex)
x, y -> x - y //오름차순
x, y -> y - x //내림차순

 

# 자바 우선순위큐 사용 예시 

- 1. 기본 오름차순 정렬

- 2. 기본 내림차순 정렬 (reverse)

- 3. Comparable 구현 정렬

- 4. Comparator 구현 정렬

- 5. 문자열(사전식) 정렬 

// Comparable || Comparator 사용...
class Person implements Comparable<Person> {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person o) {
        // 내림차순
        return o.age - this.age;
    }
}

public class example {
        public static void solution(String[] name, int[] age) {
        // 자바 기본 PriorityQueue 사용
        System.out.println("== 자바 기본 우선순위 큐 ==");
        // 우선순위: 낮은 숫자 순 (오름차순..)
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(7);
        pq.add(3);
        pq.add(1);
        pq.add(9);
        System.out.println(Arrays.toString(pq.toArray())); //[1, 3, 5, 7, 9]	

        // 우선순위: 높은 숫자 순 (내림차순..)
        PriorityQueue<Integer> pq2 = new PriorityQueue<>(Collections.reverseOrder());
        pq2.add(5);
        pq2.add(7);
        pq2.add(3);
        pq2.add(1);
        pq2.add(9);
        System.out.println(Arrays.toString(pq2.toArray())); // [9, 7, 3, 1, 5]
        
        // 3. Comparable 방식 !
        PriorityQueue<Person> pq3 = new PriorityQueue<>();
        IntStream.range(0, name.length)
                .forEach((i) -> pq.add(new Person(name[i], age[i])));
        int size = pq3.size();
        while (!pq3.isEmpty()) {
            System.out.print(pq3.poll().name + " ");
        }
        
        System.out.println();
        
        // 4. Comparator 방식 ! -> 정렬 로직은 같다..
        PriorityQueue<Person> pq4 = new PriorityQueue<>((x, y -> y.age - x.age);
        IntStream.range(0, name.length)
                .forEach((i) -> pq4.add(new Person(name[i], age[i])));
        while (!pq4.isEmpty()) {
            System.out.print(pq4.poll().name + " ");
        }
        
        // 5. 사전식 정렬 -> Comparable 혹은 Comparator 안에서 String.compareTo() 함수로 크기 비교
        PriorityQueue<Person2> pq5 = new PriorityQueue<>((x, y) -> x.name.compareTo(y.name)); //오름차순
        PriorityQueue<Person2> pq5 = new PriorityQueue<>((x, y) -> y.name.compareTo(x.name)); //내림차순
        IntStream.range(0, name.length)
                        .forEach((i) -> pq5.add(new Person(name[i], age[i])));
        while (!pq5.isEmpty()) {
            System.out.print(pq5.poll().name + " ");
        }
        
    }

    public static void main(String[] args) {
        String[] name = {"A", "B", "C", "D", "E"};
        int[] age = {30, 20, 45, 62, 35};

        solution(name, age);

    }
}