题目
将一串数字以空格间隔的方式输入,并以选择排序的方式进行升序排序,最后输出。
例如:
输入:1 3 9 5
输出:1 3 5 9
选择排序的基本思想:每次从待排序序列中选择一个关键字最小的元素(如果是降序就选择最大的),按顺序排在已排序序列的最后,直至全部排完。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
inline double stringTodouble(const string& s){
//用于将字符串转换为double实数
//因为要调用多次,将其置为内联函数
double d;
istringstream is(s);
is>>d;
return d;
}
void stringsplit(const string s,vector<double>& v){
string temp;
istringstream stream(s);
while(stream>>temp)
v.push_back(stringTodouble(temp));
}
void selectSort(vector<double>& a,int n){
double temp;
int i;
for(i=0;i<a.size()-1;i++){
temp = i;
for(int j=i+1;j<a.size();j++)
if(a[j]<a[temp])
temp = j;
int t = a[temp];
a[temp] = a[i];
a[i] = t;
}
}
void printSort(const vector<double> v){
cout<<"排序后的结果是:";
for(int x=0;x<v.size();x++)
cout<<v[x]<<" ";
}
int main()
{
string str;
vector<double> v;
cout<<"输入数字进行插入排序:"<<endl;
getline(cin,str);
stringsplit(str,v); //将数从字符串分割后放入容器
selectSort(v,v.size()); //进行选择排序
printSort(v); //输出排序后的序列
cout<<endl;
return 0;
}