CS/알고리즘

[Algorithm] 계수정렬(Counting Sort)

Ella_K 2023. 3. 13. 07:30

계수정렬(Counting Sort) 

크기를 기준으로 갯수를 세는 알고리즘

갯수를 세는 배열(counting)을 정렬하고자 하는 배열(arr)의 사이즈를 최대값으로 담기도록 설정한다.

배열을 탐색하면서 해당 값을(arr[i]) counting배열에서 인덱스로 하는 갯수를 센다. 

import java.util.Scanner;

public class p07_countingSort {
    public static void countingSort(int[] arr, int max){
        int[] counting = new int[max+1]; // 배열의 사이즈를 최대값이 담기도록 잡는다.

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

        for(int i = 1; i < max+1; i++){
            if(counting[i] != 0) {
                for(int j = 0; j < counting[i]; j++){
                    System.out.print(i+" ");
                }
            }
        }
    }

    public static void countingSort2(int[] arr, int max){
        int[] sorted_arr = new int[arr.length];
        int[] counting = new int[max+1]; // 배열의 사이즈를 최대값이 담기도록 잡는다.

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

        int t = 0;
        for(int i = 1; i < max+1; i++){
            if(counting[i] != 0) {
                for(int j = 0; j < counting[i]; j++){
                    sorted_arr[t++] = i;
                }
            }
        }

        for(int x: sorted_arr)
            System.out.print(x+" ");

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // 배열 갯수
        int max = sc.nextInt(); // 배열의 최대 값
        int[] arr = new int[n];

        for(int i = 0; i < n; i++)
            arr[i] = sc.nextInt();
        countingSort(arr, max);
    }
}

시간 복잡도

O(N)

장점

  • 빠르다.

단점

  • 배열의 최대 값에 따라 메모리가 많이 필요하다.

 


source

https://blog.naver.com/ndb796/221228361368

 

11. 계수 정렬(Counting Sort)

  우리는 지금까지 선택 정렬, 버블 정렬, 삽입 정렬, 퀵 정렬, 병합 정렬, 힙 정렬의 개념을 하나하...

blog.naver.com

https://gyoogle.dev/blog/algorithm/Counting%20Sort.html

 

계수 정렬(Counting Sort) | 👨🏻‍💻 Tech Interview

계수 정렬(Counting Sort) Comparison Sort N개 원소의 배열이 있을 때, 이를 모두 정렬하는 가짓수는 N!임 따라서, Comparison Sort를 통해 생기는 트리의 말단 노드가 N! 이상의 노드 갯수를 갖기 위해서는, 2^h

gyoogle.dev

 

'CS > 알고리즘' 카테고리의 다른 글

[자료구조] Tree의 종류  (0) 2023.03.14
[자료구조] 힙 (Heap)  (0) 2023.03.14
[Algorithm] 병합 정렬 (Merge Sort)  (0) 2023.03.13
[Algorithm] 퀵 정렬 (Quick Sort)  (0) 2023.03.12
[Algorithm] 이분 탐색(Binary Search)  (1) 2023.03.12