ํ”„๋กœ๊ทธ๋ž˜๋ฐ/Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ๊ณ„์ˆ˜ ์ •๋ ฌ Counting Sort

NaNaRin๐Ÿ™ƒ 2021. 1. 28. 20:34

 

๊ณ„์ˆ˜ ์ •๋ ฌ (Counting Sort) ์•Œ๊ณ ๋ฆฌ์ฆ˜ : 

๊ณ„์ˆ˜ ์ •๋ ฌ = ๋„์ˆ˜ ์ •๋ ฌ = ์นด์šดํŒ… ์ •๋ ฌ

์š”์†Œ์˜ ๋Œ€์†Œ ๊ด€๊ณ„๋ฅผ ํŒ๋‹จํ•˜์ง€ ์•Š๊ณ  ๋น ๋ฅด๊ฒŒ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

1. ๋ฐฐ์—ด ๋‚ด ์š”์†Œ ๊ฐ’๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•˜๋Š” ์นด์šดํŒ… ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค

2. ์นด์šดํŒ… ๋ฐฐ์—ด์˜ ์š”์†Œ์— ์ง์ „ ์š”์†Œ์˜ ๊ฐ’์„ ๋”ํ•ด์ค€๋‹ค.

 

์นด์šดํŒ… ๋ฐฐ์—ด

3. ๋ฐฐ์—ด๊ณผ ๊ฐ™์€ ํฌ๊ธฐ์˜ ์ถœ๋ ฅ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  ์ž…๋ ฅ ๋ฐฐ์—ด์˜ ์—ญ์ˆœ์œผ๋กœ ์ถœ๋ ฅ ๋ฐฐ์—ด์— ์š”์†Œ๋“ค์„ ์ฑ„์›Œ๋„ฃ๋Š”๋‹ค.

   3-1. ๋ฐฐ์—ด a์˜ ๋งจ ๋’ท ์š”์†Œ 8์„ ๊บผ๋‚ด counting[8]์„ ํ™•์ธ

   3-2. ๋ฐฐ์—ด b์˜ counting[8]-- ํ›„ counting[8] ์ž๋ฆฌ์— 8์„ ์ €์žฅ

4. ๋ฐฐ์—ด b๋ฅผ ๋ฐฐ์—ด a๋กœ ๋ณต์‚ฌํ•œ๋‹ค

์ถœ๋ ฅ ๋ฐฐ์—ด b ์ฑ„์›Œ๋„ฃ๊ธฐ 

 

 

๋ฉ”์†Œ๋“œ countingSort() : ๋ฐฐ์—ด a๋ฅผ ์นด์šดํŒ… ์ •๋ ฌ

๋งค๊ฐœ๋ณ€์ˆ˜ : int[] a, int n

 

- ์นด์šดํŒ… ์ •๋ ฌ : 

void countingSort(int[] a, int n) {
	int max = a[0];
	for(int i = 0; i < n; i++) {
		if(a[i] > max)
			max = a[i];
	}
	
	int[] counting = new int[max+1];
	int[] b = new int[n];
	
	for(int i = 0; i < n; i++) counting[a[i]]++;
	for(int i = 1; i <= max; i++) counting[i] += counting[i-1];
	for(int i = n-1; i >= 0; i--) b[--counting[a[i]]] = a[i];
	for(int i = 0; i < n; i++) a[i] = b[i];
}

 

 

 

 

์นด์šดํŒ… ์ •๋ ฌ Counting Sort :

์ตœ์„  = O(N), ํ‰๊ท  = O(N), ์ตœ์•… = O(N)

์•ˆ์ •ํ•œ ์ •๋ ฌ