counting sort
๐โโ๏ธ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ์๋ ๊ณ์์ ๋ ฌ (์นด์ดํ ์ํธ)๋ฅผ ๋ฐฐ์๋ณด๋๋ก ํ์
ํด๋น ์๊ณ ๋ฆฌ์ฆ์ O(N+K)๋ก K๋ ๊ฐ์ ๋ฒ์์ ๋ฐ๋ผ ๋ฐ๋๋ค.
์ฆ ์ต๋๊ฐ์ด ์์ ์๋ก ์ข๋ค.
์ด์ ๊ตฌํ์ ํด๋ณด์
๐ค ์์
1
int[] arr = {3,1,5,1,6,2,7,3,3};
์ด๋ฐ ๋ฐฐ์ด์ด ์๋ค๊ณ ๊ฐ์ ํ์
๊ทธ ์ดํ cnt๋ฐฐ์ด์ ๋ง๋ค์ด ๋ฐฐ์ด์ ํฌ๊ธฐ๋ max_num + 1๊น์ง ๋ง๋ค๊ณ
arr์ ์ซ์๋งํผ ์นธ์ ์ฑ์์ฃผ์ ๊ทธ๋ฌ๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ฒ์ด๋ค
1
int[] cnt = {0, 2, 1, 3, 0, 1, 1, 1}
๊ทธ๋ค์ ์ ์ผ ์ค์ํ ๋์ ํฉ์ ํด์ค์ผํ๋ค
๊ทธ๋ฌ๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ฒ์ด๋ค
1
int[] cnt = {0, 2, 3, 6, 6, 7, 8, 9};
์ด์ ๊ณ์ฐ์ ํ์ ์๋๋ ํ์ฌ๊น์ง ์งํ๋ ์ํฉ์ด๋ค.
์ด์ ๋ถํฐ ๊ฑฐ๊พธ๋ก ๊ณ์ฐ์ ํ์
arr[i]๋ฅผ cnt ๋ฐฐ์ด์ idx๋ก ์ฐพ์๊ฐ๊ณ ๊ทธ๋์ ๊ฐ์์ -1 ์ฐ์ฐํ ๋ฐฐ์ด ์๋ฆฌ๋ก ๊ทธ ๊ฐ์ ์ถ๊ฐํ๋ค.
๊ทธ๋ฆฌ๊ณ cnt ๋ฐฐ์ด์ ํด๋น idx ๊ฐ์ 1๊ฐ ์์ค๋ค.
๊ทธ ์ด์ ๋ ๊ฐ์ด ์ฌ๋ฌ๊ฐ๋ผ๋ฉด ์์ผ๋ก ์ฑ์๋ฃ๊ธฐ ์ํจ์ด๋ค.
์ด์ ๋งจ ๋ค์์๋ฅผ ๋ดค์ผ๋ ๋ค์์ ๋งจ๋ค์์ 2๋ฒ์งธ๋ฅผ ํ์ํ ์ฐจ๋ก๋ค
์ด์ด์ ๋๊ฐ์ด ์งํ๋๊ฒ ๋ค.
๋ค์
๋ค์
๋ค์
๋๋จธ์ง๋ ๋๊ฐ์ ๋ฐฉ์์ผ๋ก res ๋ฐฐ์ด์ด ์ฑ์์ง๊ฒ ๋ค
โ ์ ๋ต
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
31
32
int[] arr = {3,1,5,1,6,7,2,3,3};
int N = arr.length;
// 1. ์ต๋๊ฐ ๊ตฌํ๊ธฐ
int max = 0;
for (int i = 0; i < N; i++) {
if (arr[i] > max) max = i;
}
// 2. ์นด์ดํ
๋ฐฐ์ด
int[] cnt = new int[max + 1];
// 2-1. ์นด์ดํ
๋ฐฐ์ด ์ด๊ธฐ ์ถ๊ฐ
for (int i = 0; i < N; i++) {
cnt[ arr[i] ]++;
}
// 2-2. ์นด์ดํ
๋ฐฐ์ด ๋์ ํฉ ์ ์ฉ
for (int i = 1; i < cnt.length; i++) {
cnt[i] += cnt[i-1];
}
// 3. ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
int[] res = new int[N];
for (int i = N-1; i >= 0; i--) {
int cur_val = arr[i];
res[ cnt[ arr[i] ] - 1 ] = cur_val;
cnt[ arr[i] ]--;
}
๊ฒฐ๊ณผ
1
res = {1, 1, 2, 3, 3, 3, 5, 6, 7};







