좌표정렬

문제

설명

N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램을 작성하세요.

정렬기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다.

입력

첫째 줄에 좌표의 개수인 N(3<=N<=100,000)이 주어집니다.

두 번째 줄부터 N개의 좌표가 x, y 순으로 주어집니다. x, y값은 양수만 입력됩니다.

출력

N개의 좌표를 정렬하여 출력하세요.

예시 입력 1

5
2 7
1 3
1 2
2 5
3 6

예시 출력 1

1 2
1 3
2 5
2 7
3 6

해결방법

  • 오름차순 → 현재 - 다음 = 음수
  • 내림차순 → 다음 - 현재 = 음수

    sort() 함수는 기본적으로 오름차순 정렬.

    역순 정렬은 Collections.reverseOrder() 사용

    • Arrays.sort(arr, Collections.reverseOrder())

코드

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){
        // 파라미터 좌표와 현재 좌표를 비교하여 리턴
        // x 값이 같으면 y로 정렬, 그 반대도 있음.
        if(this.x==o.x) return this.y-o.y;
        else return this.x-o.x;
    }
}

class Main {
    public static void main(String[] args){
        Scanner kb = new Scanner(System.in);
        int n=kb.nextInt();
        ArrayList<Point> arr=new ArrayList<>();
        for(int i=0; i<n; i++){
            int x=kb.nextInt();
            int y=kb.nextInt();
            arr.add(new Point(x, y));
        }
        Collections.sort(arr);
        for(Point o : arr) System.out.println(o.x+" "+o.y);
    }
}


© 2024. Chiptune93 All rights reserved.