分析:对给出的线性整数数组进行排序,排序后进行取出前k个最小的数;
#include <iostream>
#include <array>
using namespace std ;
/*
题目:输入n个整数,输出其中最小的k个。
例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。
*/
class mainK
{
private :
int * p;
array< int , 10 > temp1;
int * pre;
int i, j, temp;
public :
mainK ()
{
p = new int [ 10 ];
this -> pre = NULL ;
}
void getarraydata()
{
for ( int i= 0 ; i< 10 ; i++)
{
std :: cin >> p[ i];
}
// for(int i=0;i<p.size();i++)
// {
// std::cout <<p[i]<<endl;
// }
}
int * quick_sort( int left, int right) //快速排序的方法
{
if ( left< right)
{
this -> i = left;
this -> j = right;
this -> temp = p[ this -> i];
while ( this -> i< this -> j)
{
while ( this -> i< this -> j&& p[ this -> j]> this -> temp)
this -> j--;
if ( this -> i< this -> j)
{
p[ this -> i] = p[ this -> j];
this -> i++;
}
while ( this -> i< this -> j&& p[ this -> i]< this -> temp)
this -> i++;
if ( this -> i< this -> j)
{
p[ this -> j] = p[ this -> i];
this -> j--;
}
}
p[ this -> i] = temp;
quick_sort( left, this -> i- 1 );
quick_sort( this -> i+ 1 , right);
}
return p;
}
void getdata()
{
for ( int i= 0 ; i< 10 ; i++)
{
cout << p[ i] << " " ;
}
}
int getmainK( int n)
{
for ( int i= 0 ; i< n; i++)
{
cout << p[ i] << " " ;
}
}
~ mainK ()
{
delete [] p;
}
};
int main()
{
// cout << "Hello World!" << endl;
int ( n);
mainK main1;
main1. getarraydata();
main1. quick_sort( 0 , 9 );
//main1.getdata();
cout<< "请输入要输出最小元素的个数:" ;
cin >> n;
main1. getmainK( n);
std :: cin. get();
return 0 ;
}