一、选择排序
就从左到右一直选择最小的到前面去
二、插入排序
从左到右把数插入有序数组
三、关于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;
}
我的代码很粗糙,很多地方可以改善,一开始我把想错了,可以看看大神的代码。