알고리즘 풀다보면 왠지 헷갈리는 정렬 메소드..
정렬 방법을 정리해보자!


1. Array


int[] arr = {3, 4, 7, 9};

// 오름차순
Arrays.sort(arr); // [3, 4, 7, 9]

// 내림차순 : reverOrder를 사용하기 위해 Wrapper Class로 변경 후 사용
Integer[] arrInt = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(arrInt, Comparator.reverseOrder()); // [9, 7, 4, 3]
Arrays.sort(arrInt, Collections.reverseOrder()); // [9, 7, 4, 3]



2. ArrayList


ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3, 4, 7, 9));

Collections.sort(list); // [3, 4, 7, 9]
Collections.sort(list, Collections.reverseOrder()); // [9, 7, 4, 3]



3. N차원 배열


Comparator.comparing()

ex. int[][] arr을 정렬

Arrays.sort(arr, Comparator.comparingInt((int[] o) -> o[0])); // 첫번째 숫자 기준 오름차순
Arrays.sort(arr, Comparator.comparingInt((int[] o) -> o[0]).reversed()); // 첫번째 숫자 기준 내림차순
Arrays.sort(arr, Comparator.comparingInt((int[] o) -> o[1])); // 두번째 숫자 기준 오름차순
Arrays.sort(arr, Comparator.comparingInt((int[] o) -> o[1]).reversed()); // 두번째 숫자 기준 내림차순



Lambda 사용 (Java 8 이상)

ex. int[][] arr을 정렬

Arrays.sort(arr, (o1, o2) -> {
    return o1[0]-o2[0]; // 첫번째 숫자 기준 오름차순
});



4. PriorityQueue


// 기본 : 오름차순
PriorityQueue<Integer> pq = new PriorityQueue<>();

// 내림차순
PriorityQueue<Integer> pqReverseOrder = new PriorityQueue<>(Collections.reverseOrder());




참고 자료



Tags: ,

Categories:

Updated:

Leave a comment