手敲快排之后懒惰了,没有手敲归并,假期的第一题就是手动实现了一下,ac了一个快排的题。
poj 2623 http://poj.org/problem?id=2623
题目大意就是输入一些数,输出他们的中位数。排序之后去中位数就可以了。
归并排序的思想网上挺容易找到的,不再赘述,直接发代码。
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn=1000000;
int A[maxn];
void Merge(int *a,int *b,int *c, int *d, int L)
{
int *X=(int *)malloc(sizeof(int)*L);
int L1=b-a+1,L2=d-c+1;
int n=0,x=0,y=0;
while(x<L1||y<L2)
{
while(x<L1&&y<L2)
X[n++]=a[x]<c[y]?a[x++]:c[y++];
while(x<L1)
X[n++]=a[x++];
while(y<L2)
X[n++]=c[y++];
}
for(n=0;n<L;++n)
a[n]=X[n];
free(X);
}
void mergesort(int *left,int *right,int step)
{
if(right-left==0);
if(right-left==1) Merge(left,left,right,right,right-left+1);
if(right-left>1)
{
mergesort(left,left+(right-left)/2,step+1);
mergesort(left+(right-left)/2+1,right,step+1);
Merge(left,left+(right-left)/2,left+(right-left)/2+1,right,right-left+1);
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;++i)
scanf("%d",&A[i]);
mergesort(A,A+n-1,0);
sort(A,A+n); //这里是与快排的比较。
printf("%.1f\n",n%2?A[n/2]*1.0:0.5*((double)A[n/2]+(double)A[n/2-1]));
return 0;
}