좌표 정렬(Compare)

최준호·2021년 8월 27일
0

알고리즘 강의

목록 보기
41/79

설명

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

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

코드

public class XYSort {
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        int input1 = in.nextInt();
        Point[] arr = new Point[input1];
        Point2[] arr2 = new Point2[input1];
        for(int i=0; i<input1; i++){
            int su1 = in.nextInt();
            int su2 = in.nextInt();
            Point p = new Point(su1,su2);
            arr[i] = p;

            Point2 p2 = new Point2(su1, su2);
            arr2[i] = p2;
        }

        solution(arr);
        for (Point p : arr) {
            System.out.print(p.x+" "+p.y);
            System.out.println();
        }
        System.out.println("-------------------------");
        Arrays.sort(arr2);
        for (Point2 p : arr2) {
            System.out.print(p.x+" "+p.y);
            System.out.println();
        }
    }
    public static void solution(Point[] arr){
        Arrays.sort(arr, (o1, o2) -> {
            if(o1.x == o2.x) return o1.y-o2.y;
            else return o1.x - o2.x;
        });
    }
    static class Point{
        int x;
        int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    static class Point2 implements Comparable<Point2>{
        int x;
        int y;

        public Point2(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public int compareTo(Point2 o) {
            if(this.x == o.x) return this.y - o.y;
            else return this.x - o.x;
        }
    }
}

Compare를 통해서 좌표를 정렬하는 방법이다. 여기선 메서드별로 볼것이 아니라 class 별로 봐야하는데 Point와 Point2를 보면 서로 다르게 정렬했지만 결과값은 동일한 것을 알수 있다.

우선 Point는 class 자체에 Comparalbe나 Comparator를 상속받지 않고 sort할때 Comparator를 직접 구현하여 sort한 방식이다.

다음으로 Point2는 class에 Comparable을 상속받아 직접 class 내에서 sort의 기준을 정하고 실제 정렬이 실행되는 sort() 에서는 따로 구현하지 않고 바로 실행하면 point때와 동일하게 실행된다.

Compare에 대해서 학습되지 않은 사람들은 java의 정석이나 java 관련 서적을 참고하거나 직접 검색해보길 바란다!

class 구현시 Comapare를 구현해서 바로 정렬시키는 방법도 있다!

profile
코딩을 깔끔하게 하고 싶어하는 초보 개발자 (편하게 글을 쓰기위해 반말체를 사용하고 있습니다! 양해 부탁드려요!) 현재 KakaoVX 근무중입니다!

0개의 댓글