좌표정렬

Red Culture·2021년 7월 4일

N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하려면 (x가 같으면 y기준으로) 다음과 같은 과정을 거친다.

오름차순이 되려면 Comparable 인터페이스를 구현한 클래스에서 compareTo 메서드를 재정의할 때 this 객체 (ex) 10) 와 파라미터로 넘어온 객체 (ex) 20) 이 되기 때문에 compateTo를 하게 되면 음수가 되도록 한다.
(반대로 내림차순이 되려면 양수가 되도록 만든다.)

Collections.sort는 Comparable 인터페이스의 compareTo 메서드를 통해서 정렬한다.

class Point implements Comparable<Point>{
    public int x;
    public int y;

    public 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;
        else return this.x-o.x;
    }
}

public class Main7 {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        ArrayList<Point> arrayList = new ArrayList<>();

        for(int i = 0; i < n; i++) {
            int x = kb.nextInt();
            int y = kb.nextInt();
            arrayList.add(new Point(x, y));
        }

        // 리스트 정렬
        Collections.sort(arrayList);

        for(Point o : arrayList) System.out.println(o.x + " " + o.y);
    }
}
profile
자기 개발, 학습 정리를 위한 블로그

0개의 댓글