题解 | #输入n个整数,输出其中最小的k个#
输入n个整数,输出其中最小的k个
http://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c
算法总结第二篇,希尔排序和起泡和快速排序(递归)
#include <algorithm>
#include <vector>
using namespace std;
int mypartion(int low,int high,vector<int> &v){
int temp = v[low];
while(low<high){
while(low<high&&(temp<=v[high])) high--;
v[low]=v[high];
while(low<high&&(temp>=v[low])) low++;
v[high] = v[low];
}
v[low] = temp;
return low;
}//快排递归
vector<int> & mysort(int low,int high,vector<int> & v){//起泡不需要low和high
/*int n = v.size();
for(int i = n/2;i>=1;i/=2){
for(int j = i;j<n;j++){
if(v[j]<v[j-i]){
int temp,k;
temp = v[j];
for(k = j-i;k>=0&&(temp<v[k]);k-=i){
v[k+i]=v[k];
}
v[k+i]=temp;
}//if
}//内层for
}//外层for,希尔排序*/
/*int n = v.size();
for(int i = 1;i<n;i++){
for(int j = 0;j<n-i;j++){
while(v[j]>v[j+1]&&(j<n-1)){
swap(v[j],v[j+1]);
j++;
}
}
}//起泡排序*/
if(low<high){
int m = mypartion(low, high, v);
mysort(low, m-1, v);
mysort(m+1, high, v);
}
return v;
}
int main() {
int n,k;
while(cin>>n>>k){
vector<int> v;
int temp=0;
for(int i = 0;i<n;i++){
cin>>temp;
v.push_back(temp);
}
v=mysort(0,n-1,v);
for(int j = 0;j<k;j++){
cout<<v[j]<<' ';
}
}
}