Search
Duplicate
🚍

[Java] 정렬, Sort , Comparator, Comparable, 오름 차순, 내림 차순

생성일
2022/11/17 23:43
태그
공개여부

Arrays.sort()

Arrays.sort({배열이름}) ⇒ 쉽게 오름차순 정렬이 가능하다.
평균적으로 O(nlog(n)) 정도 시간이 걸리지만, 최악의 경우 O(n^2) 이다.
import java.util.Arrays; public class sort_example { public static void main(String[] args){ int[] arrInt = {1,4,5,23,5,6,2,4}; String[] arrString = {"A","E","C","B","D"}; Arrays.sort(arrInt); Arrays.sort(arrString); System.out.print("arrInt : "); for(int num : arrInt){ System.out.print(num + ", "); } System.out.println(); System.out.print("arrString : "); for(String s : arrString){ System.out.print(s + " ,"); } }
Java
복사
위와 같이 정렬이 가능하고 결과는 아래와 같다.

Comparable/ Comparator

Comparable과 Comparator 을 사용하여 내림차순이나 원하는 조건 커스텀이 가능하다.
Comparable 인터페이스의 ComparaTo() 메서드를 원하는 조건으로 오버라이드하거나 ,익명 인터페이스 Comparator를 구현한 Class내 comparable() 메소드를 원하는 정렬조건으로 오버라이드하여 sort 메소드 호출시 Comparator 클래스를 명시만 해주면된다.
주의 할점은 Primitive Type의 배열에는 적용 불가하니, Integer와 같은 Wrapper 클래스를 이용해야만 한다.
import java.util.Arrays; import java.util.Comparator; public class sort_example { public static void main(String[] args){ Integer[] arrInt = {1,4,5,23,5,6,2,4}; String[] arrString = {"A","E","C","B","D"}; Arrays.sort(arrInt,Comparator.reverseOrder()); Arrays.sort(arrString,Comparator.reverseOrder()); System.out.print("arrInt : "); for(int num : arrInt){ System.out.print(num + ", "); } System.out.println(); System.out.print("arrString : "); for(String s : arrString){ System.out.print(s + " ,"); } } }
Java
복사
결과는 아래와 같다.
Comparable 과 Comparator는 모두 인터페이스인데, 이 말은 Comparable 혹은 Comparator 을 사용하고자 한다면 인터페이스 내에 선언된 메소드를 구현해야만 한다는 뜻이다.
선언된 메소드를 확인해보면,
Comparable 내에 CompareTo(T o) 메소드가 하나가 선언되어 있다. 즉, Comparable을 사용하고자 한다면 ComparableTo 메소드를 재정의(오바라이드/Override) 해주어야 한다는 것이다.
Comparator 내에 선언된 메소드가 많지만, 실질적으로 구현해야할 것은 Compare(T o1, T o2)이다.
정리 하자면 아래와 같다.
인터페이스
구현해야할 메소드
Comparable
CompareTo(T o)
Comparator
compare(T o1, T o2)
이 두 인터페이스의 근본적인 목적은 ‘객체’를 비교 하는것이다.
흔히들 사용하는 부등호를 사용한 비교는 primitive type에서만 사용되는데 이는 자바에서 제공하기 때문에 쉽게 사용이 가능하다.
하지만 객체를 비교, 예를 들자면 학생 클래스에 수학 성적, 과학 성적이 들어있고 수학 성적만으로 비교를 하고 싶다면, 위의 인터페이스를 활용할 수 있다.
그럼 이 두 인터페이스의 차이는 뭘까.
일단 생긴 모양만 본다면 parameter의 갯수가 다른것을 확인 할 수 있다.
Comparable은 자기 자신과 들어오는 parameter를 비교하는것이고,
Comparator는 두개의 parameter를 비교한다.
먼저 Comparable을 보자면
class Student implements Comparable<Student> { int math; int science; Student(int math, int science) { this.math = math; this.science = science; } @Override public int compareTo(Student o) { if(this.math> o.math) { //양수 return 1; } else if(this.math== o.math) { //0 return 0; } else { return -1; //음수 } } }
Java
복사
이런 식으로 만들 수도 있지만 더 간단하게는
class Student implements Comparable<Student> { int math; int science; Student(int math, int science) { this.math = math; this.science = science; } @Override public int compareTo(Student o) { return this.math - o.math; } }
Java
복사
이런식으로 자기 자신에서 비교 할 값을 빼주면 자기가 크면 양수 , 같으면 0 , 작으면 음수를 반환한다. 위 방식이 코드도 짧고 간단하지만, 뺄셈 과정에서 자료형의 범위를 넘어버리는 경우도 있기 때문에 그럴 가능성이 있다면 부등호를 사용하여 작성하는것이 더 효율적이다.
Comparator 도 위 코드와 마찬가지다.
class Student implements Comparator<Student> { int math; int science; Student(int math, int science) { this.math = math; this.science = science; } @Override public int compare(Student o1, Student o2) { return o1.math - o2.math; } }
Java
복사
하지만 이 방법은 단점이 있다.
o1객체와 o2 객체를 사용하기 위해 다른 객체가 필요하다. 즉 객체 두개를 비교하기 위해 새로운 Student 객체를 만들어야 한다는것이다.
이를 해결하기 위해 익명 클래스를 활용한다.
public class sort_example { public static void main(String[] args){ Comparator<student> compare = new Comparator<student>() { @Override public int compare(student student, student t1) { return student.math - t1.math; } }; public static class student{ int math; int science; student(int math,int science){ this.math = math; this.science = science; } } }
Java
복사
익명 클래스는 이런식으로 사용가능하다.