/*****************************************************
*
* Main: 归并排序
* Code by: Xiangjie.Huang
* Date: 2014/08/18
* Blog: http://blog.163.com/surgy_han
*
* <----------------Details: start------------>
*
* (1) 分治法
* (2) 例如二路归并, 谁小谁上谁队列往后一位
*
* <----------------Details: end-------------->
*
*****************************************************/
//#pragma comment(linker, "/STACK:61400000,61400000")
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define pi 3.1415926535897932385
#define LL64 __int64
#define LL long long
#define oo 2147483647
#define N 1010
#define M 210
#define INF 1e9
int data[N];
int L[N];
int R[N];
void InputData(int n)
{
for (int i = 0; i < n; i++)
{
scanf("%d", &data[i]);
}
}
void Output(int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", data[i]);
}
printf("\n");
}
void Merge(int l, int mid, int r)
{
for (int i = 0; i < mid - l + 1; i++)
{
L[i] = data[l + i];
}
L[mid - l + 1] = oo;
for (int i = 0; i < r - mid; i++)
{
R[i] = data[mid + i + 1];
}
R[r - mid] = oo;
int ld = 0, rd = 0;
for (int i = l; i <= r; i++)
{
if (L[ld] < R[rd])
{
data[i] = L[ld++];
}
else
{
data[i] = R[rd++];
}
}
}
void Sort_of_Merge(int l, int r)
{
int mid = (l + r) >> 1;
if (l < r)
{
Sort_of_Merge(l, mid);
Sort_of_Merge(mid + 1, r);
Merge(l, mid, r);
}
}
int main()
{
int n;
//freopen("data.in", "r", stdin);
//freopen("data.out", "w", stdout);
while (~scanf("%d", &n))
{
InputData(n);
Sort_of_Merge(0, n - 1);
Output(n);
}
return 0;
}
归并排序
最新推荐文章于 2024-08-12 19:32:44 发布