4.1 排序

一、选择排序

就从左到右一直选择最小的到前面去

二、插入排序

从左到右把数插入有序数组

三、关于sort()

头文件

algorithm

参数

sort ( 起始地址 , 终止地址+1 , cmp (比较函数) )

比较函数cmp的编写

考虑到我们需要按照自己想要的方式对数据进行排序,可以自定义比较规则。

bool cmp(node a,node b){
	if(a.y==b.y) return a.x>b.x;
	return a.y>b.y;
}

上述代码中 node表示数据类型,可以使基本数据int,double等,也可以时自定义的结构体和类。最后的使用效果为容器内的元素按照cmp函数的返回值为true时对应的规则进行排序
如果使用上述cmp函数对node数组排序,最后得到的结果就是按照属性y的值从大到小排序,如果属性y值相同,则按照x值从大到小进行排序。

四、计算排名

在通过sort函数将某个类按照自定义的规则排序以后,需要继续进行计算每个对象的排名,得分相同的排名相同,可以在对象中加入属性 r 表示对应的排名信息。

int r = 1;//表示当前排名
for(int i = 0;i<len;i++){
	if(i!=0&&node[i].score!=node[i-1].score)
		r = i+1;//更新排名
	node[i] = r; 
}

五、例题

PAT A1025 Ranking

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student
{
    string res;
    int loc;
    double score;
    int rank;
    Student(string a, int b, double c) : res(a), loc(b), score(c) {}
};
bool cmp(Student a, Student b)
{
    if (a.score == b.score)
    {
        return a.res < b.res;
    }
    return a.score > b.score;
}
void loc_rank(vector<Student> &students)
{
    int a = 1;
    for (int i = 0; i < students.size(); i++)
    {
        if (i != 0 && students[i].score != students[i - 1].score)
        {
            a = i + 1;
        }
        students[i].rank = a;
    }
}
int main()
{
    int a, b ;
    string res;
    double score;
    cin >> a;
    vector<vector<Student>> students(a);
    vector<Student> all;
    for (int i = 1; i <= a; i++)
    {
        cin >> b;
        for (int j = 0; j < b; j++)
        {
            cin >> res >> score;
            students[i - 1].push_back(Student(res, i, score));
        }
        sort(students[i-1].begin(),students[i-1].end(),cmp);
        //计算本地的排名
        loc_rank(students[i - 1]);
        all.insert(all.end(), students[i - 1].begin(), students[i - 1].end());
    }
    sort(all.begin(), all.end(), cmp);
    a = 1;
    cout << all.size();
    for (int i = 0; i < all.size(); i++)
    {
        if (i != 0 && all[i].score != all[i - 1].score)
        {
            a = i + 1;
        }
        cout << endl
             << all[i].res << " " << a << " " << all[i].loc << " " << all[i].rank;
    }
    return 0;
}

我的代码很粗糙,很多地方可以改善,一开始我把想错了,可以看看大神的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值