成绩排序

成绩排序

http://www.nowcoder.com/questionTerminal/8e400fd9905747e4acc2aeed7240978b

冒泡排序法具有稳定性

#include <iostream>
#include <vector>

using namespace std;

struct Student
{
    string name;
    unsigned score;
    Student(string str, unsigned sig):name(str),score(sig)
    {

    }
};

void bubleSort(vector<Student>& vec, bool flag)
{
    bool isOrder = true;
    for(unsigned i = 0; i < vec.size() - 1; ++i)
    {
        isOrder = true;
        for(unsigned j = 0; j < vec.size() - 1 - i; ++j)
        {
            if(flag)//1从小到大
            {
                if(vec[j].score > vec[j + 1].score)
                {
                    swap(vec[j], vec[j + 1]);
                    isOrder = false;
                }
            }
            else
            {
                if(vec[j].score < vec[j + 1].score)
                {
                    swap(vec[j], vec[j + 1]);
                    isOrder = false;
                }
            }
        }

        if(isOrder) break;
    }
}

int main()
{
    unsigned n = 0, flag = 0, score = 0;
    string name;
    vector<Student> vec;
    while(cin >> n >> flag)
    {
        while(n--)
        {
            cin >> name >> score;
            Student stu(name, score);
            vec.push_back(stu);
        }
        bubleSort(vec, flag);
        for(auto &node : vec)
        {
            cout << node.name << " " << node.score << endl;
        }
        vec.clear();
    }
    return 0;
}
全部评论

相关推荐

03-29 14:19
门头沟学院 Java
你背过凌晨4点的八股文么:加油同学,人生的容错率很高,只是一个暑期罢了,后面还有很多机会!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务