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

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ์…ธ ์ •๋ ฌ Shell Sort

NaNaRin๐Ÿ™ƒ 2021. 1. 26. 15:54

 

์…ธ ์ •๋ ฌ (Shell Sort) ์•Œ๊ณ ๋ฆฌ์ฆ˜ : 

์‚ฝ์ž… ์ •๋ ฌ ์˜ ์žฅ์ ์€ ์‚ด๋ฆฌ๊ณ  ๋‹จ์ ์€ ๋ณด์™„ํ•˜์—ฌ ์ข€ ๋” ๋น ๋ฅด๊ฒŒ ์ •๋ ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜, ๋ถˆ์•ˆ์ • ์ •๋ ฌ.

์ •๋ ฌํ•  ๋ฐฐ์—ด์˜ ์š”์†Œ๋ฅผ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ  ๊ฐ ๊ทธ๋ฃน๋ณ„๋กœ ์‚ฝ์ž… ์ •๋ ฌ์„ ์ˆ˜ํ–‰ํ•˜๊ณ ,

๊ทธ ๊ทธ๋ฃน์„ ํ•ฉ์น˜๋ฉด์„œ ์ •๋ ฌ์„ ๋ฐ˜๋ณตํ•˜์—ฌ ์š”์†Œ์˜ ์ด๋™ ํšŸ์ˆ˜๋ฅผ ์ค„์ž„

 

์‚ฝ์ž… ์ •๋ ฌ์˜ ์žฅ/๋‹จ์ 

   ์žฅ์  : ์ •๋ ฌ์„ ๋งˆ์ณค๊ฑฐ๋‚˜ ์ •๋ ฌ์„ ๋งˆ์นœ ์ƒํƒœ์— ๊ฐ€๊นŒ์šฐ๋ฉด ์ •๋ ฌ ์†๋„๊ฐ€ ๋นจ๋ผ์ง„๋‹ค

   ๋‹จ์  : ์‚ฝ์ž…ํ•  ์œ„์น˜๊ฐ€ ๋ฉ€๋ฆฌ ๋–จ์–ด์ ธ ์žˆ์œผ๋ฉด ์ด๋™(์‚ฝ์ž…)ํ•ด์•ผ ํ•˜๋Š” ํšŸ์ˆ˜๊ฐ€ ๋งŽ์•„์ง„๋‹ค

 

์…ธ ์ •๋ ฌ์€ ์ „์ฒด์˜ ๋ฐฐ์—ด์„ ํ•œ๋ฒˆ์— ์ •๋ ฌํ•˜์ง€ ์•Š๊ณ 

์ •๋ ฌํ•ด์•ผ ํ•  ๋ฐฐ์—ด์„ ์ผ์ •ํ•œ ๊ธฐ์ค€์— ๋”ฐ๋ผ ๋ถ„๋ฅ˜ํ•˜์—ฌ ์—ฐ์†์ ์ด์ง€ ์•Š์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ถ€๋ถ„ ๊ทธ๋ฃน์„ ๋งŒ๋“ค์–ด ๊ฐ ๊ทธ๋ฃน์„ ์‚ฝ์ž… ์ •๋ ฌํ•œ๋‹ค.

๋ถ€๋ถ„ ๊ทธ๋ฃน์„ ๊ตฌ์„ฑํ•  ๋•Œ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๊ฐ K๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ถ”์ถœํ•˜์—ฌ ๋งŒ๋“œ๋Š”๋ฐ, ์ด K๋ฅผ ๊ฐ„๊ฒฉ(gap)์ด๋ผ ํ•œ๋‹ค.

๊ฐ ๋‹จ๊ณ„๋ณ„๋กœ ํ•˜๋‚˜์˜ ๋ถ€๋ถ„ ๊ทธ๋ฃน์˜ ์š”์†Œ ๊ฐœ์ˆ˜๋Š” ์ฆ๊ฐ€, gap์€ ๊ฐ์†Œํ•˜๋ฉฐ gap์ด 1์ด ๋  ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

์‹ค์ œ๋กœ ์—ฌ๋Ÿฌ๊ฐœ์˜ ๋ฐฐ์—ด๋กœ ๋‚˜๋ˆ„๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๋‹จ์ˆœํžˆ gap ๊ฐ’์œผ๋กœ ๊ฐ„๊ฒฉ์„ ์ฃผ์–ด ๋ถ€๋ถ„ ๊ทธ๋ฃน์ด ๋งŒ๋“ค์–ด์ง„ ๊ฒƒ ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•œ๋‹ค.

 

์‚ฝ์ž… ์ •๋ ฌ์— ๋น„ํ•ด ์ •๋ ฌ ํšŸ์ˆ˜๋Š” ์ฆ๊ฐ€ํ•˜์ง€๋งŒ ์ „์ฒด์ ์œผ๋กœ๋Š” ์š”์†Œ์˜ ์ด๋™ ํšŸ์ˆ˜๊ฐ€ ์ค„์–ด๋“ค์–ด ๋” ํšจ์œจ์ ์ด๋‹ค.

 

int shell = {8, 1, 4, 2, 7, 6, 3, 5}

1. 4์นธ๋งŒํผ ๋–จ์–ด์ง„ ์š”์†Œ๋ฅผ ๋ชจ์•„ ๋ฐฐ์—ด์„ 4๊ฐœ์˜ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๊ฐ ๊ทธ๋ฃน๋ณ„๋กœ ์‚ฝ์ž… ์ •๋ ฌ ( gap = 4 )

 

๋ฐฐ์—ด shell์˜ ์…ธ ์ •๋ ฌ ๊ณผ์ • - 1

 

2. 1๋ฒˆ ์ •๋ ฌ์„ ๋งˆ์นœ ์ƒํƒœ์—์„œ 2์นธ๋งŒํผ ๋–จ์–ด์ง„ ์š”์†Œ๋ฅผ ๋ชจ์•„ ๋ฐฐ์—ด์„ 2๊ฐœ์˜ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๊ฐ ๊ทธ๋ฃน๋ณ„๋กœ ์‚ฝ์ž… ์ •๋ ฌ ( gap = 2 )

 

๋ฐฐ์—ด shell์˜ ์…ธ ์ •๋ ฌ ๊ณผ์ • - 2

 

3.  2๋ฒˆ ์ •๋ ฌ์„ ๋งˆ์นœ ์ƒํƒœ์—์„œ ์‚ฝ์ž…์ •๋ ฌ ( gap = 1 )

 

shell์˜ ๊ฒฝ์šฐ gap๊ฐ’์„ 4, 2, 1(gap/2)๋กœ ๊ฐ์†Œํ•˜๋ฉฐ 7ํšŒ์˜ ์ •๋ ฌ๋กœ ์ •๋ ฌ์„ ๋งˆ์ณค๋‹ค.

 

์…ธ ์ •๋ ฌ์€ gap๊ฐ’์— ๋”ฐ๋ผ ์‹œ๊ฐ„์ด ํฌ๊ฒŒ ๋‹ฌ๋ผ์ง€๊ธฐ ๋•Œ๋ฌธ์— gap๊ฐ’์˜ ์„ค์ •์ด ์ค‘์š”ํ•œ๋ฐ

๋ณดํ†ต ์…ธ ์ •๋ ฌ์—์„œ gap์€ ์ „์ฒด ๋ฐฐ์—ด์˜ ์š”์†Œ ์ˆ˜ N์„ 2๋กœ ๋‚˜๋ˆ„๋Š” ๊ฐ’์œผ๋กœ ์ง„ํ–‰ํ•˜์ง€๋งŒ, ๋ณดํ†ต ์ง์ˆ˜๋ณด๋‹ค๋Š” ํ™€์ˆ˜๊ฐ€ ๋” ๋น ๋ฅด๊ณ , 3์œผ๋กœ ๋‚˜๋ˆ„๊ณ  1์„ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ(N/3+1)๊ฐ€ ๋” ๋น ๋ฅด๋‹ค๊ณ  ์•Œ๋ ค์ ธ ์žˆ๋‹ค.

 

๋ฉ”์„œ๋“œ shellSort() : ๊ธธ์ด๊ฐ€ n์ธ ๋ฐฐ์—ด a๋ฅผ ์…ธ ์ •๋ ฌ

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

 

- ์…ธ ์ •๋ ฌ

void shellSort(int[] a, int n) {
	int h = n;
	do {
		h = h/3+1;
		for(int i = h; i < n; i++) {
			int j;
			int tmp = a[i];
			for(j = i-h; j >= 0 && a[j] > tmp; j -= h) {
				a[j + h] = a[j];
			}
			a[j+h] = tmp;
		}
	} while(h != 1);
}

 

 

 

 

์…ธ ์ •๋ ฌ Shell Sort :

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

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