Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- redux-toolkit
- useDispatch
- react
- sw expert academy
- 항해플러스
- 자바
- 리액트
- 매일메일
- programmers
- Get
- redux
- json-server
- C++
- 테코테코
- createSlice
- react-router
- redux-saga
- SW
- axios
- 프로그래머스
- java
- maeil-mail
- 이코테
- 항해99
- Python
- 알고리즘
- react-redux
- JavaScript
- Algorithm
- 코딩테스트합격자되기
Archives
- Today
- Total
Binary Journey
[Algorithm] Counting Sort(계수 정렬) 본문
반응형
인프런 강의 12강에 대한 리뷰이다.
계수 정렬은 범위 조건이 있는 정렬이다.
강의에서 나온 조건의 경우 "5이하의 수를 정렬"이었다.
Counting Sort의 경우 조건에 맞는 수가 몇 개인지 (주어진 숫자 전체를 훑으며) 센 다음 수를 나열하기 때문에
시간복잡도는 O(N) 이다.
** C++
#include <stdio.h>
int main(void) {
int temp;
int count[5];
int array[30] = {
1, 3, 2, 4, 3, 2, 5, 3, 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;
}
** Javascript
위 C++ 소스를 Javascript 로 바꾸면 아래와 같다.
function countingSort() {
let count = new Array(5).fill(0);
let array = [
1, 3, 2, 4, 3, 2, 5, 3, 1, 2,
3, 4, 4, 3, 5, 1, 2, 3, 5, 2,
3, 1, 4, 3, 5, 1, 2, 1, 1, 1
];
for (var i = 0; i < array.length; i++) {
count[array[i] - 1]++;
}
const answer = count.reduce((acc, curr, i) => acc += (curr != 0) ? (`${i + 1}`).repeat(curr) : "", "");
console.log(answer);
}
countingSort();
reduce 만세
** Java
public class Main
{
public static void main(String[] args) {
int[] count = {0, 0, 0, 0, 0};
int[] array = {
1, 3, 2, 4, 3, 2, 5, 3, 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 < array.length; i++) {
count[array[i] - 1]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
for (int j = 0; j < count[i]; j++) {
System.out.printf("%d",i + 1 );
}
}
}
}
}
반응형
'Algorithm > 알고리즘 스터디(2021.07)' 카테고리의 다른 글
[Algorithm] Stack (스택) (0) | 2021.08.25 |
---|---|
[Algorithm] 심화 정렬 알고리즘 문제 풀이 (백준 1181, 1431, 10989) (0) | 2021.08.10 |
[Algorithm] Heap Sort(힙 정렬) (0) | 2021.08.04 |
[Algorithm] Merge Sort(병합 정렬) (0) | 2021.08.04 |
[Algorithm] 백준 sort 문제풀이 (0) | 2021.07.29 |