오늘 백준 문제를 풀다가 2차원 배열을 정렬해야 하는 상황에서 아무리 생각을 해봐도 방법이 떠오르지 않았다.
그래서 찾아보니 몇가지 방법이 있다고 한다.
Comparator, Comparable
Comparator의 공식 문서를 찾아보면,
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#method.summary
Comparator (Java Platform SE 8 )
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. In the foregoing description, the notation sgn(expression) designates the mathematical s
docs.oracle.com
엄청나게 많은 메소드들이 있어서 어질어질하지만, 실질적으로 구현해야하는것은 compare(T o1, T o2)임을 알 수 있다.
Comparator대신에 Comparable을 사용해도 되는데, 가장 중요한점은 둘다 인터페이스 이기 때문에 메소드를 '반드시 구현' 해야한다.
마찬가지로 Comparable의 공식 문서를 찾아보면,
docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#method.summary
Comparable (Java Platform SE 8 )
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Lists (and arrays) of o
docs.oracle.com
Comparable 인터페이스에는 compareTo(T o) 메소드 하나가 선언되어있는 것을 볼 수 있다. 즉, Comparable 인터페이스를 쓰려면 compareTo 메소드를 구현해야하고, Comparator 인터페이스를 쓰려면 compare 메소드를 구현해야 한다.
원래 하려고 했던 2차원 배열을 정렬하기위해서 문제가

이렇게 입력을 받았을경우, 오름차순을 해야하는게 첫번째 과정이였는데 간단하게 Comparator를 이용해서 코드를 짜보면
int arr[][] = new int[][]{{1,4},{3,5},{0,6},{5,7},{3,8},{5,9},{6,10},{8,11},{8,12},{2,13},{12,14}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0]-o2[0]; // 첫번째 숫자 기준 오름차순
//return o2[0]-o1[0]; // 첫번째 숫자 기준 내림차순
//return o1[1]-o2[1]; // 두번째 숫자 기준 오름차순
//return o2[1]-o1[1]; // 두번째 숫자 기준 내림차순
}
});
이런식으로 구현이 된다.
Lamda 사용(JAVA 8 이상)
람다식을 이용해서 좀더 간결하게 구현하는 방법도 있다. Array.sort 부분만
Arrays.sort(arr, (o1, o2) -> {
return o1[0]-o2[0]; //첫번째 기준 오름차순
});
이런식으로 바꿔주면 더 간단해진다.
'알고리즘 공부' 카테고리의 다른 글
| 백준(BOJ)-1260 DFS와 BFS (DFS,BFS 알고리즘) (0) | 2023.05.12 |
|---|---|
| 백준(BOJ)-1931 회의실 배정[JAVA] (그리디 알고리즘) (1) | 2023.05.12 |
| 정렬 알고리즘(Sort Algorithm)정리[JAVA] (1) | 2023.05.08 |
| 백준(BOJ)-1018 체스판 다시 칠하기 [JAVA] (브루트 포스 알고리즘) (1) | 2023.05.04 |
| [java] 정렬알고리즘(삽입,선택,버블) (0) | 2022.03.28 |
댓글