[快速排序/归并排序] 100000个数 HUSTOJ2496

 

题目描述

输入n组测试数据,从小到大排序.

输入

输出

样例输入

2
3
3 6 5
4
8 5 9 7

样例输出

3 6 5
5 7 8 9

提示

(1  <= n <= 100000)

 

 

#include 

using namespace std;
int a[100000];
void paixu(int le,int ri)
{
	int l=le,r=ri;
	int t=a[(le+ri)/2];
	while(l<=r)
	{
		while(a[l]=t时停止
		while(a[r]>t) r--;
		if(l<=r)
		{
			swap(a[l],a[r]);  //值交换
			l++;r--; //下一位
		}
	} //结束时 r在l左一位
	if(le>k;
	while(k--)
	{
		int n;cin>>n;
		for(int i=0;i>a[i];
		paixu(0,n-1);
		cout<
#include 
#define ll long long
#define db double
using namespace std;
const int inf = 1e9;
const ll INF = 1e18;
const ll mod = 998244353;

const int mn = 1e5 + 10;
const int mm = 4e3 + 10;

int a[mn], b[mn];
void Merge(int l1, int r1, int l2, int r2, int id)
{
	id--;
	int t1 = l1, t2 = l2;
	while (t1 <= r1 && t2 <= r2)
	{
		if (a[t1] <= a[t2]) {b[++id] = a[t1], t1++;}
		if (a[t1] > a[t2]) {b[++id] = a[t2], t2++;}
	} /// 比较每组的最前一个数,将较小的放入b数组,然后指针后移
	// 其中一组已经放完
	if (t1 == r1 + 1)
	{
		for (int i = t2; i <= r2; i++)
			b[++id] = a[i];
	}
	else if (t2 == r2 + 1)
	{
		for (int i = t1; i <= r1; i++)
			b[++id] = a[i];
	}
}

bool cmp(int a, int b) {return a < b;}
void mergesort(int L, int R)
{
	if (L >= R) return;
	int mid = (L + R) / 2;
	mergesort(L, mid);
	mergesort(mid + 1, R);

	/// STL库algorithm 左闭右开 保证子区间有序 可自定义cmp
	merge(a + L, a + mid + 1, a + mid + 1, a + R + 1, b + L, cmp);
	//Merge(L, mid, mid + 1, R, L);

	for (int i = L; i <= R; i++) a[i] = b[i];
}

int main()
{
	int n; scanf("%d", &n);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	mergesort(1, n);
	for (int i = 1; i < n; i++) printf("%d ", a[i]);
	printf("%d\n", a[n]);

	return 0;
}

 

你可能感兴趣的:(分治法,模板)