ํฉ๋ณ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ (Merge Sort):
์ ๋ ฌํ ๋ฐฐ์ด์ ๋ ์ด์ ๋๋ ์ง ์ ์๋ ๋ฐฐ์ด๋ก ๋๋์ด(Divide) ๋ฐฐ์ด ๋จ์๋ณ๋ก ์ ๋ ฌ(Conquer)ํด ๋๊ฐ๋ ์๊ณ ๋ฆฌ์ฆ.
์๊ฐ ๋ณต์ก๋ : O(n log n)
ใ กใ กใ กใ กใ ก
#include <stdio.h>
#define MAX 8
int tmp[MAX];
void merge(int list[], int left, int mid, int right) {
int l_idx, r_idx, c_idx, t_idx;
// l_idx : ์ผ์ชฝ ๋ฐฐ์ด์ ์ปค์
// r_idx : ์ค๋ฅธ์ชฝ ๋ฐฐ์ด์ ์ปค์
// c_idx : ์์์๊ฐ ๋ค์ด๊ฐ์ผํ๋ ๋ฐฐ์ด์ ํ์ฌ ์์น
// t_idx : ๋จ์ ์์๋ฅผ ํ๊บผ๋ฒ์ ์ ์ฅํ ๋ ์ฌ์ฉํ ์์ ์ธ๋ฑ์ค
l_idx = c_idx = left;
r_idx = mid + 1;
while (l_idx <= mid && r_idx <= right) { // l_idx <= 3 && r_idx <= 7
if (list[l_idx] <= list[r_idx])
tmp[c_idx++] = list[l_idx++];
else
tmp[c_idx++] = list[r_idx++];
}
if (l_idx>mid) {
for (t_idx = r_idx; t_idx <= right; t_idx++)
tmp[c_idx++] = list[t_idx];
}
else {
for (t_idx = l_idx; t_idx <= mid; t_idx++) // (t_idx = 2; t_idx <= 3; t_idx++)
tmp[c_idx++] = list[t_idx];
}
// ๋ณต์ฌ๋ณธ์ ๋ด์ฉ์ ์๋ณธ์ ๋ณต์ฌ
for (t_idx = left; t_idx <= right; t_idx++) {
list[t_idx] = tmp[t_idx];
}
printf("SORTED : ");
l_idx = -1;
while (tmp[++l_idx] != 0) {
printf("%d ", tmp[l_idx]);
}
printf("\n");
}
void merge_sort(int list[], int left, int right) {
int mid;
if (left == right) { // ํ์ฌ ๋ด์ผํ๋ ๋ฐฐ์ด์ด ์์๊ฐ 1๊ฐ๋ฟ์ธ ๋ฐฐ์ด์ด๋?
return;
}
mid = (left + right) / 2; // ๊ฐ์ด๋ฐ ์ธ๋ฑ์ค๋ฅผ ๊ตฌํจ
merge_sort(list, left, mid); // divide (left ~ mid)
merge_sort(list, mid + 1, right); // divide( mid +1 ~ right )
merge(list, left, mid, right); // conquer
}
int main() {
int arr[MAX] = { 7, 8, 5, 4, 6, 1, 3, 2 };
printf("Given array is \n"); //์ฒ์์ ์ซ์ ๋ฐฐ์ด ์ถ๋ ฅ.
for (int i = 0; i < MAX; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
merge_sort(arr, 0, MAX - 1); // merge sort ํธ์ถ.-> ์ฌ๊ทํจ์ ์์.
printf("\nSorted array is \n"); // sort์ฒ๋ฆฌ๋ ์ซ์์ด ์ถ๋ ฅ.
for (int i = 0; i < MAX; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
ใ กใ กใ กใ กใ ก
':: C_ ๐ฉ > ์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฃ๊ตฌ์กฐ] by C์ธ์ด #09 [stack ๊ตฌ์กฐ] (0) | 2021.03.30 |
---|---|
[์๋ฃ๊ตฌ์กฐ] by C์ธ์ด -#08 [Quick sort] (0) | 2021.03.29 |
[์๋ฃ๊ตฌ์กฐ] by C์ธ์ด #07 [insertion sort] (0) | 2021.03.28 |
[์๋ฃ๊ตฌ์กฐ] #03 by C์ธ์ด [์ฌ๊ทํธ์ถ ์๊ณ ๋ฆฌ์ฆ] (0) | 2021.03.26 |
[์๋ฃ๊ตฌ์กฐ] by c์ธ์ด #02 ์๊ฐ๋ณต์ก๋, ๊ณต๊ฐ๋ณต์ก๋, Big-O ํ๊ธฐ๋ฒ (0) | 2021.02.16 |
๋๊ธ