티스토리 뷰

728x90
반응형

문제

 

N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.

 

입력

 

첫째 줄에 수의 개수 N(1 ≤ N ≤ 10,000,000)이 주어진다. 

둘째 줄부터 N개의 줄에는 수가 주어진다.

이 수는 10,000보다 작거나 같은 자연수이다.

 

출력

 

첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.

 

풀이

 

카운팅 정렬은 대상 배열의 크기 N과 원소중 최댓값 k에 따라 O(N + k)의 시간 복잡도를 가진다.

 

이는 배열의 크기가 작고, 수의 범위가 좁을수록 무시무시한 속도를 자랑하는데,

 

이번 문제는 그 카운팅 정렬을 구현해보라는 문제이다.

 

다른 글에서 구현했으므로, 여기서는 그냥 가져다 쓴다.

 

2022.12.27 - [Development/Java] - [Algorithm]카운팅 정렬(Counting Sort)

 

[Algorithm]카운팅 정렬(Counting Sort)

카운팅 정렬은 말 그대로 세어서 정렬하는 방식이다. 그래서 무엇을 세느냐 하면, 아래에서 보겠지만 정렬 대상이 대는 원소의 등장 횟수를 전부 센다. 이후 원소의 최댓값에 따라 누적합을 보

gnidinger.tistory.com

import java.io.*;
import java.util.Arrays;

public class Prob10989 {

    private static int[] result;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

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

        int[] target = new int[n];

        for (int i = 0; i < n; i++) {
            target[i] = Integer.parseInt(br.readLine());
        }

        countingSortImpl(target);

        for (int i = 0; i < n; i++) {
            bw.write(result[i] + "\n");
        }
        bw.flush();
        bw.close();
    }

    public static void countingSortImpl(int[] target) {

        int[] counting = new int[Arrays.stream(target).max().getAsInt() + 1];
        result = new int[target.length];

        for (int i = 0; i < target.length; i++) { // Counting
            counting[target[i]]++;
        }

        for (int i = 1; i < counting.length; i++) { // 누적 합
            counting[i] += counting[i - 1];
        }

        for (int i = target.length - 1; i >= 0; i--) { // 정렬
            counting[target[i]]--; // 해당 인덱스 값을 하나 줄여주고
            result[counting[target[i]]] = target[i]; // 줄여진 수를 인덱스 삼아 result에 값 채우기
        }
    }
}
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함