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

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ํž™ ์ •๋ ฌ Heap Sort - ๋ถ€์—ฐ

NaNaRin๐Ÿ™ƒ 2021. 1. 28. 16:58

 

ํž™ ์ •๋ ฌ (Heap Sort) ์•Œ๊ณ ๋ฆฌ์ฆ˜ : 

'๋ถ€๋ชจ์˜ ๊ฐ’์ด ์ž์‹์˜ ๊ฐ’๋ณด๋‹ค ํ•ญ์ƒ ํฌ๋‹ค or ์ž‘๋‹ค' ๋ฅผ ๋งŒ์กฑํ•˜๋Š” ์™„์ „์ด์ง„ํŠธ๋ฆฌ ํž™ ์˜ ํŠน์„ฑ์„ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌ ์ˆ˜ํ–‰. 

์„ ํƒ ์ •๋ ฌ ์„ ์‘์šฉํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

 

 

 

 

๋ฉ”์†Œ๋“œ swap() : a[idx1] ๊ณผ a[idx2] ๋ฅผ ๊ตํ™˜

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

 

๋ฉ”์†Œ๋“œ donwHeap() : ๋ฐฐ์—ด a์˜ index left ๋ถ€ํ„ฐ right ๊นŒ์ง€ ์š”์†Œ๋ฅผ ํž™์œผ๋กœ ๋งŒ๋“ ๋‹ค

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

๋ฉ”์†Œ๋“œ heapSort() : ๊ธธ์ด๊ฐ€ n์ธ ๋ฐฐ์—ด a๋ฅผ ํž™ ์ •๋ ฌ

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

 

- ํž™ ์ •๋ ฌ :

void swap(int[]a, int idx1, int idx2) {
	int t = a[idx1];
	a[idx1] = a[idx2];
	a[idx2] = t;
}

void downHeap(int[] a, int left, int right) {
	int temp = a[left];
	int child;
	int parent;
	
	for(parent = left; parent <(right+1)/2; parent = child) {
		int cl = parent * 2 +1;
		int cr = cl + 1;
		child = (cr <= right && a[cr] > a[cl]) ? cr : cl;
		if(temp >= a[child])
			break;
		a[parent] = a[child];
	}
	a[parent] = temp;
}
	
void heapSort(int[] a, int n) {
	for(int i = (n-1)/2; i >= 0; i--)
		downHeap(a, i, n - 1);
	
	for(int i = n-1; i > 0; i--) {
		swap(a, 0, i);
		downHeap(a, 0, i-1);
	}
}

 

 

 

 

ํž™ ์ •๋ ฌ Heap Sort :

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

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