๋ถํ ์ ๋ณต
๐โโ๏ธ๋ถํ ์ ๋ณต
๋ถํ ์ ๋ณต์ ํ์ ์ํ๋ฅผ ์ด์ฉํ ๋ฐฉ์์ด๋ค.
์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๋ค ์ง๋๊ณ ์์ ์ ๋์์ ์ํํ๋ค.
void divide(int lt, int rt)
{
int mid;
int p1, p2, p3;
if (lt < rt)
{
mid = (lt + rt) / 2;
divide(lt, mid);
divide(mid + 1, rt);
p1 = lt;
p2 = mid + 1;
p3 = lt;
while (p1 <= mid && p2 <= rt)
{
if (arr[p1] < arr[p2])
temp[p3++] = arr[p1++];
else
temp[p3++] = arr[p2++];
}
while (p1 <= mid)
{
temp[p3++] = arr[p1++];
}
while (p2 <= rt)
{
temp[p3++] = arr[p2++];
}
for (int i = lt; i <= rt; ++i)
{
arr[i] = temp[i];
}
}
}
์ด์ ์ 39๋ฒ ๋ ๋ฐฐ์ดํฉ์น๊ธฐ ๋ฌธ์ ์ ๋น์ทํ๋ค.
์๊ฐ ๋ณต์ก๋๋ O(nlogn)
์ด๋ผ๊ณ ํ๋ค.
๋ถํ ์ ๋ณต ์๊ฐ์๋ ๋ ๋ง๋ค ์์ผ๊ฒ ๋ค.
๐์ ์ฒด ์ฝ๋
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int arr[100], temp[100];
void divide(int lt, int rt)
{
int mid;
int p1, p2, p3;
if (lt < rt)
{
mid = (lt + rt) / 2;
divide(lt, mid);
divide(mid + 1, rt);
p1 = lt;
p2 = mid + 1;
p3 = lt;
while (p1 <= mid && p2 <= rt)
{
if (arr[p1] < arr[p2])
temp[p3++] = arr[p1++];
else
temp[p3++] = arr[p2++];
}
while (p1 <= mid)
{
temp[p3++] = arr[p1++];
}
while (p2 <= rt)
{
temp[p3++] = arr[p2++];
}
for (int i = lt; i <= rt; ++i)
{
arr[i] = temp[i];
}
}
}
void solve()
{
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> arr[i];
divide(1, n);
for (int i = 1; i <= n; ++i)
cout << arr[i] << " ";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
freopen("input.txt", "rt", stdin);
solve();
return 0;
}