๋ฐ˜๊ฐ€์›Œ์š”! ํ—ˆ๋ธŒ์ž…๋‹ˆ๋‹ค!

์ €๋Š” ๊ฐœ๋ฐœ์ž๋ฅผ ํ˜„๋Œ€ ์—ฐ๊ธˆ์ˆ ์‚ฌ๋ผ๊ณ  ํ‘œํ˜„ํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค. ๊ฐœ๋ฐœ์„ ๊ณต๋ถ€ํ•˜๋ฉฐ ๋Š๋‚€ ์ ๋“ค๊ณผ ์ด์•ผ๊ธฐ๋ฅผ ๊ธฐ๋กํ•˜๋Š” ๊ณต๊ฐ„์ž…๋‹ˆ๋‹ค.

์ž๋ฃŒ๊ตฌ์กฐ

[์ž๋ฃŒ๊ตฌ์กฐ] ์ƒํ–ฅ์‹ ํž™์ •๋ ฌ heapsort

mmin.h 2020. 8. 13. 22:16

์•ˆ๋…•ํ•˜์„ธ์š” ์ฃผ์ธ์žฅ H์ž…๋‹ˆ๋‹ค. 

์˜ค๋Š˜์€ ํž™์ •๋ ฌ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

ํž™์ •๋ ฌ์€ ํž™ํŠธ๋ฆฌ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌ์„ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. 

ํž™์€ ์ตœ์†Ÿ๊ฐ’์ด๋‚˜ ์ตœ๋Œ“๊ฐ’์„ ๋น ๋ฅด๊ฒŒ ์ฐพ์•„๋‚ด๊ธฐ ์œ„ํ•ด ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•˜๋Š” ํŠธ๋ฆฌ์ž…๋‹ˆ๋‹ค. 

์—ฌ๊ธฐ์„œ ์™„์ „ ์ด์ง„ํŠธ๋ฆฌ๋ž€ ๋ถ€๋ชจ๋…ธ๋“œ(root)์— 2๊ฐœ์˜ ์ž์‹๋…ธ๋“œ(c)๋ฅผ ๊ฐ€์ง„ ํ˜•ํƒœ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค. 

ํž™์—๋Š” ์ตœ๋Œ€ํž™๊ณผ ์ตœ์†Œํ•ฉ์ด ์กด์žฌํ•˜๊ณ , ์ตœ๋Œ€ ํž™์€ ๋ถ€๋ชจ๋…ธ๋“œ๊ฐ€ ์ž์‹๋…ธ๋“œ๋ณด๋‹ค ์ปค์•ผํ•ฉ๋‹ˆ๋‹ค. 

 

ํž™์ •๋ ฌ์„ ํ•˜๊ธฐ์œ„ํ•ด์„  ์ •ํ•ด์ง„ ๋ฐ์ดํ„ฐ๋ฅผ ํž™๊ตฌ์กฐ๋กœ ๋งŒ๋“  ํ›„์— ์‹œ์ž‘ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. 

ํž™ ์ •๋ ฌ์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด์„  ํž™ ์ƒ์„ฑ ์•Œ๊ณ ๋ฆฌ์ฆ˜(heapifiy Algorithm)์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. 

ํŠน์ • ๋…ธ๋“œ์˜ ๋‘ ์ž์‹ ์ค‘ ๋” ํฐ ์ž์‹๊ณผ ์ž์‹ ์„ ๋ฐ”๊พธ๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

 

์˜ˆ๋ฅผ ๋“ค์–ด 

   1

 4    9

2 3 4 4 

 

   9

 4    4

2 3 4 1 

๋กœ ํž™๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค๊ณ  ํŠน์ • ๋…ธ๋“œ 9์™€ 1์„ ์„œ๋กœ ๋ฐ”๊พธ์–ด ์ค๋‹ˆ๋‹ค 

 

   1

 4    4

2 3 4  9

๊ทธ ํ›„ 9๋ฅผ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค์„ ๋‹ค์‹œ ์ตœ๋Œ€ํ•ญ์„ ๋งŒ๋“ค์–ด์ฃผ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•˜๋ฉด

 

    2

 3    2

4 4 4  9  

์˜ ํ˜•ํƒœ๋กœ ์ •๋ ฌ์ด ๋ ๊ฒƒ์ž…๋‹ˆ๋‹ค. 

 

๊ทธ๋Ÿผ ์œ„์—์„œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ธ๋ฑ์Šค์— ๋„ฃ์–ด์ฃผ๋ฉด ๋˜๊ฒ ์ฃ . 

์ด๋•Œ ํž™์ •๋ ฌ์˜ ์ „์ฒด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” 

ํž™์ƒ์„ฑ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(log N)์ด๊ณ  ์ „์ฒด ๋ฐ์ดํ„ฐ์˜ ๊ฐฏ์ˆ˜๊ฐ€ N์ด๋ฏ€๋กœ 

O(log N * N)์ด ๋˜๊ฒ ์Šต๋‹ˆ๋‹ค. 

#include <stdio.h>
#define HEAPSIZE 9

int heap[HEAPSIZE] = { 1,5,3,6,2,6,6,4,9 };

//ํž™ ๊ตฌ์กฐ ๋งŒ๋“ค๊ธฐ 

int main(void) {
	for (int i = 1; i < HEAPSIZE; i++) {
		int c = i; 
		do {
			int root = (c - 1) / 2;
			if (heap[root] < heap[c]) {
				int temp = heap[root];
				heap[root] = heap[c];
				heap[c] = temp;
			} c = root; 
		} while (c != 0);
	}
	//ํฌ๊ธฐ๋ฅผ ์ค„์—ฌ๊ฐ€๋ฉฐ ํž™ ์ •๋ ฌ
	for (int i = HEAPSIZE - 1; i >= 0; i--) {
		int temp = heap[0]; 
		heap[0] = heap[i]; 
		heap[i] = temp; 
		int root = 0; 
		int c = 1; 
		//์ž์‹ ์ค‘์— ํฐ ๊ฐ’์ด ์žˆ๋Š”์ง€ ํ™•์ธ 
		do {
			c = 2 * root + 1; 
			if (c < i - 1 && heap[c] < heap[c + 1]) {
				c++;
			}
		//root ๊ฐ’์ด ๋” ํฌ๋‹ค๋ฉด ๊ต์ฒด 
			if (c < i && heap[root] < heap[c]) {
				temp = heap[c];
				heap[c] = heap[root];
				heap[root] = temp; 
			}
			root = c; 
		} while (c < i);
	}
	for (int i = 0; i < HEAPSIZE; i++) {
		printf("%d ", heap[i]);
	}
	return 0;
}