//寻找中项
#include<iostream>
#include<stdlib.h>
#define N 10 
using namespace std;
struct s
{
int sa;//记录小于v的元素个数
int sb;//记录等于v的元素个数
}Return;
s partition(int a[],int q,int n,int begin,int end);
int select(int a[],int begin,int end,int k);
void main()
{

    int a[N]={7,3,6,2,5,4,8,9,1,10};
//for(int i=0;i<N;i++)
// a[i]=rand();
for(int i=0;i<N;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"中项是:";
    cout<<select(a,0,9,4)<<endl;
}s partition(int a[],int q,int n,int begin,int end)
{
int j=-1;
 int temp;
for(int i=begin;i<end;i++)  //寻找小于q的元素
{
if(a[i]<q)
{
j++;
temp=a[i];
a[i]=a[j];
a[j]=temp; }
}
Return.sa=j+1;
for(i=j+1;i<end;i++)//寻找等于q的元素
{
if(a[i]==q)
{
j++;
            temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
Return.sb=j+1-Return.sa;
//for(i=begin;i<end;i++)
// cout<<a[i]<<" ";
return Return;
}int select(int a[],int begin,int end,int k)
{
int v=rand()%(end-begin+1);
int pivot=a[v+begin];
s Return1=partition(a,pivot,N,begin,end);
if(k<=Return1.sa)
select(a,begin,Return1.sa-1,k);
else if(k<=Return1.sa+Return1.sb)
return pivot;
else
        select(a,Return1.sa+Return1.sb,end,k-Return1.sa-Return1.sb-1);
}