본문 바로가기
알고리즘

좌표정렬(compareTo)

by (ㅇㅁㅇ^) 2023. 9. 4.

Comparable<T> 인터페이스를 활용한다.

 compareTo 메서드로 객체를 비교해서 Arrays.sort(arr)로 정렬한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Point implements Comparable<Point> {
    public int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    @Override
    public int compareTo(Point obj) {
        if(this.x == obj.x) {
            return this.y - obj.y;// 오름차순(1 -> 5) : 1-5(음수)가 되어야 한다.
        } else {// 내림차순(5 -> 1) : 1-5(음수)가 되어야 한다. obj.y - this.y
            return this.x - obj.x;
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Point> arr = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            arr.add(new Point(x, y));
        }
        Collections.sort(arr);
        for (Point point : arr) {
            System.out.println(point.x + " " + point.y);
        }
    }
cs

 

 

 

출처 : 인프런 자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

https://st-lab.tistory.com/243

'알고리즘' 카테고리의 다른 글

stream 사용  (0) 2023.09.06
이분탐색  (0) 2023.09.05
삽입정렬  (0) 2023.09.01
버블정렬  (0) 2023.09.01
선택정렬  (0) 2023.09.01