[Java, 알고리즘&자료구조] Array custom 정렬

zhzkzhffk·2022년 12월 2일
0
post-thumbnail

정적 배열 정렬 하는 방법은 원래 오름차순(naturalOrder), 내림차순(reverseOrder)

오름차순

int[] a = {5, 1, 2, 3, 4, 7};
Arrays.sort(a);
System.out.println(Arrays.toString(a));

// System.out.println(a)  // 참조 값만 나온다.



내림차순

원시타입은 내림차순으로 정렬할 수 없다.

```java
Integer[] a = {5, 1, 2, 3, 4, 7};
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));



2차원 배열 (start, end), (y, x) 정렬

// 백준 1744 회의실 배정 문제
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        // 2차원 배열 start, end를 담고 있는
        final int[][] arr = new int[n][2];

        StringTokenizer st;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            arr[i][0] = Integer.parseInt(st.nextToken());
            arr[i][1] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(arr, (o1, o2) -> {
            if (o1[1] == o2[1]) {
                return o1[0] - o2[0];
            }
            return o1[1] - o2[1];
        });

        int cnt = 0;
        int end = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i][0] >= end) {
                end = arr[i][1];
                cnt++;
            }
        }

        System.out.println(cnt);
    }
}
 Arrays.sort(arr, (o1, o2) -> {
            if (o1[1] == o2[1]) {
                return o1[0] - o2[0];
            }
            return o1[1] - o2[1];
 });

2차원 배열도 Reference 즉, 클래스 정렬

// 백준 1744 회의실 배정 문제
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        // 2차원 배열 start, end를 담고 있는
        final Schedule[] arr = new Schedule[n];

        StringTokenizer st;
        int startTime, endTime;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            startTime = Integer.parseInt(st.nextToken());
            endTime = Integer.parseInt(st.nextToken());

            arr[i] = new Schedule(startTime, endTime);
        }

        Arrays.sort(arr, (o1, o2) -> {
            if (o1.end == o2.end) {
                return o1.start - o2.start;
            }
            return o1.end - o2.end;
        });

        int cnt = 0;
        int end = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i].start >= end) {
                end = arr[i].end;
                cnt++;
            }
        }

        System.out.println(cnt);
    }

    static class Schedule {

        int start, end;

        public Schedule(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

}
    
profile
Backend Developer

0개의 댓글