在前一篇的基础上,随即返回N个数。
返回第k小数,须将N个数进行排序。
方法有两种
第一,将N个数排序,返回a[k-1];
第二,将前k个数排序,剩下的数逐个与a[k-1]比较,如果小于a[k],则调到正确位置,如果大于则忽略。
我采用的是第一种方法,以后在后续文章里加入第二种方法以及可能更好的方法
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int N,k,c,i,j;
cout<<"Please input N and k:";
cin>>N>>k;
int *a=new int[N];
srand((unsigned)time(NULL));
cout<<"100 random whitout sort:"<<endl;
for(i=0;i<N;i++)
{
a[i]=rand()%100;
cout<<a[i]<<" ";
if((i+1)%5==0)
cout<<endl;
}
for(i=0;i<N;i++)
{
for(j=i;j<N;j++)
{
if(a[i]>a[j])
{
c=a[i];
a[i]=a[j];
a[j]=c;
c=0;
}
}
}
for(i=0;i<N;i++)
cout<<a[i]<<endl;
cout<<"the k number is:"<<a[k-1]<<endl;
return 0;
}