728x90
백준 1181 단어 정렬
우리가 해야할 것은 단어 정렬이니 기본적으로 정렬할 배열의 타입은 String 이 될 것이다. 즉 T 는 String 이 된다는 것이다.
이렇게 Comparator 의 타입을 넣었으면, 다음으로 해야할 것은 compare 메소드를 오버라이딩하는 것이다. 즉, 아래 코드가 기본형이 되겠다.
String[] arr = new String[N]; // 배열에 단어가 이미 초기화 되었다고 가정
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
/*
정렬방법 구현
*/
}
});
기본적으로 양수일경우 Arrays.sort()에서 정렬 알고리즘에 의해 위치를 바꾸고, 0 이나 음의 정수인 경우는 두 객체의 위치는 바뀌지 않는다.
예로들어 { 2, 1, 3 } 이라는 배열이 있고, public int compare(int a1, int a2) { return a1 - a2 } 가 있다고 가정해보자.
그렇다면 맨 처음 a1 은 2 가 될테고, a2 는 1이 된다. 즉, 2 - 1 = 1 이므로 양수가 반환되기 때문에 a1 과 a2, 즉 2 와 1 의 위치가 서로 바뀌게 된다. 그러면 { 1, 2, 3 } 이 되겠다.
그 다음 a1, a2 는 각각 2 와 3이 될테고, 2 - 3 = -1 이므로 음수가 반환되어 두 객체 2와 3은 위치가 바뀌지 않는다.
이렇게 compare 메소드는 3가지 반환값에 의해 두 객체(인자)의 우선순위를 판단하고, 이를 정렬알고리즘 안에서 위치를 바꾸거나 그대로 둔다.
String[] arr = new String[N]; // 배열에 단어가 이미 초기화 되었다고 가정
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// 단어 길이가 같을 경우
if(s1.length() == s2.length()} {
return s1.compareTo(s2); // 사전 순 정렬
}
// 그 외의 경우
else {
return s1.length() - s2.length();
}
}
});
출처
https://st-lab.tistory.com/112
Comparable 정렬
public class Student implements Comparable<Student>{
public int no;
public int score;
public Student(int no, int score) {
super();
this.no = no;
this.score = score;
}
@Override
public String toString() {
return "Student [no=" + no + ", score=" + score + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return this.score - o.score;
}
}
Comparator 정렬
public static class StudentComparator implements Comparator<Student>
{
@Override
public int compare(Student o1, Student o2) {
return -(o1.score-o2.score);
}
}
lamba 정렬
Arrays.sort(arr,(o1,o2) -> Integer.compare(o1.score, o2.score));
사용 방법
// Comparable 정렬
Arrays.sort(arr);
// Comparator 정렬
Arrays.sort(arr,new StudentComparator());
// 람다 정렬
Arrays.sort(arr,(o1,o2) -> Integer.compare(o1.score, o2.score));
728x90
'언어 > JAVA' 카테고리의 다른 글
자바 문자열 뒤집기 (0) | 2021.08.06 |
---|---|
자바 문자열 뒤집기 (0) | 2021.08.06 |
자바 조합 생성 (0) | 2021.08.03 |
java 순열, 중복 순열, 조합, 중복 조합 (0) | 2021.08.03 |
StringBuilder (0) | 2021.08.02 |