본문 바로가기

알고리즘공부

계수정렬(Counting Sort)

범위 조건에 한해서 매우 빠른 알고리즘 : O(N)

크기를 기준으로 갯수를 세기만 하면 됨.

#include <stdio.h>

int main(void){
    int temp;
    int count[5];
    int array[30] = {
        1,3,2,4,3,2,5,1,2,
        3,4,4,3,5,1,2,3,5,2,
        3,1,4,3,5,1,2,1,1,1
    };
    for(int i =0;i<5;i++){
        count[i]=0;
    }
    for(int i =0;i<30;i++){
        count[array[i]-1]++;
    }
    for(int i= 0;i<5;i++){
        if(count[i]!=0){
            for(int j =0;j<count[i];j++){
                printf("%d ", i+1);
            }
        }
    }
    return 0;
}

 

count의 크기에 크게 의존적 (데이터의 편차가 작을 때 사용)

 

댓글