Backend/Java

[Java] 이차원 배열 정렬하기 CompareTo()

meong_j 2022. 5. 8. 17:52
728x90
반응형

arr ={ { 2, 7}, {1, 3}, {1, 2}, {2, 5}, {3, 6} } 인 이차원 배열을 { {1, 2}, {1, 3}, {2, 5}, {2, 7}, {3, 6} }로 정렬시키려고 한다.

일차원 배열 같은 경우에는 Arrays.sort(arr); 함수로 자동으로 정렬이 되지만,

이차원 배열은 CompareTo() 함수를 사용하여 크기비교를 해주어야 한다.

class Main {

    public static void main(String[] args) {
        Main t = new Main();
        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);
    }
}

배열을 선언 받고, ArrayList 를 오름차순으로 먼저 정렬해준다.

Collections.sort(arr);

 

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;//y 오름차순 리턴(음수)
               //내림차순  return o-y - this.y;
        else return this.x - o.x;// x 오름차순 리턴
               //내림차순  return o-x - this.x;
    }
}

(x, y) 좌표를 담는 Point라는 생성자를 생성하고 Comparable<Point> implements 하여 Point 객체를 정렬한다. 

compareTo() 메소드를 오버라이드 하여 오름차순, 내림차순의 경우를 정의 해준다.

x값이 같으면 y값을 빼서 y값을 정렬시키고, 아닌 경우 x값을 정렬시킨다.

 

 

반응형