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

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

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

[์ž๋ฃŒ๊ตฌ์กฐ] ๋ณ‘ํ•ฉ์ •๋ ฌ merge sort

mmin.h 2020. 8. 6. 15:23

์•ˆ๋…•ํ•˜์„ธ์š” ์ฃผ์ธ์žฅ H์ž…๋‹ˆ๋‹ค. ์˜ค๋Š˜์€ ๋ณ‘ํ•ฉ์ •๋ ฌ์— ๋Œ€ํ•ด ๋ฐฐ์›Œ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

๋ณ‘ํ•ฉ์ •๋ ฌ์— ์žˆ์–ด ํ‚ค์›Œ๋“œ๋Š” ํ€ต์ •๋ ฌ๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ถ„ํ•  ์ •๋ณต์„ ์ฑ„ํƒํ•œ๋‹ค๋Š” ๊ฑด๋ฐ์š”. 

์ฐจ์ด์ ์€ ํ”ผ๋ฒ—์ด ์กด์žฌํ•ด์„œ ๋žœ๋คํ•˜๊ฒŒ ๋‚˜๋ˆ„๋Š” ํ€ต๊ณผ ๋‹ฌ๋ฆฌ ๋ณ‘ํ•ฉ์ •๋ ฌ์€ 

์ •ํ™•ํžˆ ๋ฐ˜์”ฉ ๋‚˜๋ˆ•๋‹ˆ๋‹ค.

 

"์ผ๋‹จ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๋‚˜์ค‘์— ํ•ฉ์ณ์„œ ์ •๋ ฌํ•˜๋ฉด ์–ด๋–จ๊นŒ?"๋ž€ ํ‚ค์›Œ๋“œ๋ฅผ ์ƒ๊ฐํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. 

๊ทธ๋ฆฌ๊ณ  ํ€ต์ •๋ ฌ๊ณผ ๋‹ฌ๋ฆฌ O(N*log N)์„ ํ•ญ์ƒ ๋ณด์žฅํ•ด์ค๋‹ˆ๋‹ค. 

 

์˜ˆ๋ฅผ ๋“ค์–ด 7 6 5 9 2 1 5 3 ๋ผ๊ณ  ํ•œ๋‹ค๋ฉด 

2์˜ ๋ฐฐ์ˆ˜๋กœ ์ชผ๊ฐœ์ง€๊ธฐ ๋–„๋ฌธ์— ๋ถ™์–ด์žˆ๋Š” ๊ฒƒ๋ผ๋ฆฌ ๋น„๊ตํ›„์— 

67 59 12 35 ๊ฐ€ ๋˜๊ณ  

5679 1235

12355679 ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. 

 

//O(N*log N) ๋ถ„ํ•  ์ •๋ณต ์ฑ„ํƒ, ์ •ํ™•ํžˆ ๋ฐ˜์”ฉ ๋‚˜๋ˆ”, 
//ํ•ญ์ƒ nlogn๋ณด์žฅ

//์ผ๋‹จ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๋‚˜์ค‘์— ํ•ฉ์ณ์„œ ์ •๋ ฌํ•˜๋ฉด ์–ด๋–จ๊นŒ?
//ํ”ผ๋ฒ—๊ฐ’์ด ์—†๊ณ  ํ•ญ์ƒ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ”
//ํ•ฉ์น ๋• 2์˜ ๋ฐฐ์ˆ˜๋งŒํผ ํ•ฉ์นจ  

#include <stdio.h>
# define number 8
int sorted[8]; 
//์ •๋ ฌ ๋ฐฐ์—ด์€ ๋ฐ˜๋“œ์‹œ ์ „์—ญ๋ณ€์ˆ˜๋กœ ์„ ์–ธ
//์ถ”๊ฐ€์ ์ธ ๋ฐฐ์—ด์ด ํ•„์š”ํ•œ๋ฐ ํ•„์š”ํ• ๋•Œ๋งˆ๋‹ค ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๋Š”๊ฒŒ ๋น„ํšจ์œจ์ 
//๋ชจ๋“  ํ•จ์ˆ˜๊ฐ€ ๊ณตํ†ต์ ์œผ๋กœ sorted ๋ฐฐ์—ด์„ ์‚ฌ์šฉ 

void merge(int a[], int m, int middle, int n) {
	int i = m;
	int j = middle + 1; 
	int k = m;
	//์ž‘์€ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์— ์‚ฝ์ž…. 
	while (i <= middle && j <= n) {
		if (a[i] <= a[j]) {
			sorted[k] = a[i];
			i++;
		}
		else {
			sorted[k] = a[j];
			j++;
		}
		k++;
	}
	//๋‚จ์€ ๋ฐ์ดํ„ฐ๋„ ์‚ฝ์ž… 
	if (i > middle) {
		for (int t = j; t <= n; t++) {
			sorted[k] = a[t];
			k++;
		}
	}
	else{
		for (int t = i; t <= middle; t++) {
			sorted[k] = a[t];
			k++;
		}
	}
	//์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ์‚ฝ์ž… 
	for (int t = m; t <= n; t++) {
		a[t] = sorted[t];
	}
}

void mergeSort(int a[], int m, int n) {
	//์ด์™ธ์˜ ๊ฒฝ์šฐ๋Š” ํฌ๊ธฐ๊ฐ€ 1๊ฐœ์ธ ๊ฒฝ์šฐ 
	if (m < n) {
		int middle = (m + n) / 2;
		mergeSort(a, m, middle);
		mergeSort(a, middle + 1, n);
		merge(a, m, middle, n);
	}
}

int main(void) {
	int array[number] = { 7,6,5,8,3,5,9,1 };
	mergeSort(array, 0, number - 1);
	for (int i = 0; i < number; i++) {
		printf("%d ", array[i]);
	}
	return 0; 
}