ALGORITHM

[JAVA] 알고리즘 : 정렬- 좌표 정렬(compareTo)

연듀 2022. 7. 27. 09:56


import java.util.*;

class Point implements Comparable<Point> {// 포인트라는 클래스 객체를 정렬한다.
    public int x, y;
    Point(int x, int y){
        this.x=x;
        this.y=y;
    }

    @Override
    public int compareTo(Point o){
        if(this.x==o.x) return this.y-o.y; // x가 같으면 y를 비교
        // 오름차순 정렬이므로 this.y-o.y 는 음수
        else return this.x-o.x;
    }
}
public class Main {

    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); // 정렬의 기준은 compareTo()
        for(Point o:arr) System.out.println(o.x+" "+o.y);
    }
}

 

Comparable

Comparable 인터페이스를 상속 받아서 클래스의 기본 정렬 기준을 재정의한다.

 

this값과 매개변수로 받은 o가 오름차순으로 정렬이 되려면, this - o 가 음수가 되면 된다. 

반대로 내림차순으로 정렬이 되게 하려면  o - this 가 음수가 되어야 한다.

즉, 음수 값이 리턴되게 만들면 된다. 

 

 

Collection.sort(객체)

사용시 대상 객체가 정렬된다. 그 기준은 위에서 Comparable 인터페이스로 정의한 기준에 따라 정렬된다.