#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int partion(vector<int>&v,int low,int high){
int key = v[low];
while(low < high){
while(low<high && v[high]>= key){
high--;
}
if(low<high){
v[low++] = v[high];
}
while(low<high && v[low]<= key){
low++;
}
if(low<high){
v[high--] = v[low];
}
}
v[low] = key;
return low;
}
void getKnum(vector<int>&v,int k){
if (v.size() == 0 || k>v.size())
{
return ;
}
int start = 0;
int end = v.size()-1;
int index = partion(v,start,end);
while (index != k-1)
{
if (index > k-1)
{
end = index - 1;
index = partion(v,start,end);
}
else
{
start = index + 1;
index = partion(v,start,end);
}
}
sort(v.begin(),v.begin()+k);
for (int i=0;i<k;i++)
{
cout<<v[i]<<" ";
}
}
int main(){
vector<int>v;
int n,t;
while(cin>>t){
v.push_back(t);
if (getchar() == '\n')
{
break;
}
}
int k = v[v.size()-1];
v.pop_back();
getKnum(v, k);
return 0;
}
数组的最小K个数字,按序输出
最新推荐文章于 2024-05-29 21:52:24 发布
本文详细介绍了使用C++实现的快速排序算法,包括分区函数的实现细节,以及如何通过快速排序找到数组中前K个最小元素的具体过程。此外,还展示了如何从标准输入读取整数并进行排序的完整代码。
5万+

被折叠的 条评论
为什么被折叠?



