在O (n)时间以较小常数找出中位数
思路:
先准备两个辅助数
mid1和mid2
然后再根据中位数的定义快速算
常数比那个基于快排的小
#include<unistd.h>
#include<iostream>
using namespace std;
template<class T>
T get_mid(T* a, int l)
{
a-=1;
int mid1_num,mid2_num;
mid1_num=1,mid2_num=2;//keep mid1num<kip2num
if(a[1]>a[2])
{
swap(mid1_num,mid2_num);
}
for( int i=3; i<=l; ++i)
{
if(i%2)
{
if(a[i]>a[mid1_num]&&a[i]<a[mid2_num])
{
mid1_num=a[i];
continue;
}
if(a[i]>a[mid2_num])
{
mid1_num=mid2_num;
mid2_num=i;
continue;
}
}
if(a[i]<a[mid1_num])
{
mid2_num=mid1_num;
mid1_num=i;
continue;
}
if(a[i]>a[mid1_num]&&a[i]<a[mid2_num])
{
mid2_num=i;
}
}
if(l%2==0)
{
return (a[mid2_num]+a[mid1_num])/2;
}
return a[mid1_num];
}
int main()//test main function
{
int n,ans;
cin>>n;
int a[n];
for(int i=0; i<n; ++i)
{
cin >>a[i];
}
ans=get_mid<int>(a,n);
cout<<ans;
}