将一串数字以空格间隔的方式输入,并以选择排序的方式进行升序排序,最后输出

题目

将一串数字以空格间隔的方式输入,并以选择排序的方式进行升序排序,最后输出。
例如:
输入: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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值