PAT 第四讲 排序

Posted 陵游gentian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 第四讲 排序相关的知识,希望对你有一定的参考价值。

排序方法

插入排序

特征:从前往后排序,前半段是已经排好的有序,后半段是与原数组同序
每次往后排,都会与前面进行一个交换

堆排序

每次从堆中取出最大值,并放入后方序列中,后半段是原数组中最大的k个,并且已经排好序

结构体重载比较符号

// 排序规则	按照 1. total 降序 2. cnt 降序 3. id 升序 进行的排序 
bool operator<(const Student &t) const 
	if (total != t.total) return total > t.total;
	if (cnt != t.cnt) return cnt > t.cnt;
	return id < t.id;

自定义比较函数cmp(调用 sort() 时使用)

// id 升序
bool cmp1(Student a, Student b) 
    return a.id < b.id;

// 1. name 升序 2. id 升序
bool cmp2(Student a, Student b) 
    if(a.name != b.name)
        return a.name < b.name;
    return a.id < b.id;

// 1. grade 升序 2. id 升序
bool cmp3(Student a, Student b) 
    if (a.grade != b.grade)
        return a.grade < b.grade;
    return a.id < b.id;

计算排名(可以有并列)

主要说思路和代码实现,并放上两个代码段
思路,首先数组要排好序,然后如果 i != 0 && student[i].total != student[i - 1].total 则排名 +1,否则排名不变

 for (int i = 0, rank = 1; i < res.size(); i++) 
        // 计算排名
        if (i && res[i].total != res[i - 1].total)
            rank = i + 1;
        printf("%d %s\\n", rank, res.name.c_str());
 
// 对第i个地区的同学进行排序
for (int j = 0; j < local[i].size(); j++) 
	if (j == 0 || local[i][j].grade != local[i][j - 1].grade)
		local[i][j].local_rank = j + 1;
	else
		local[i][j].local_rank = local[i][j - 1].local_rank;
	all.push_back(local[i][j]);     // 将第i个地区的所有同学加入总排名中


作者:嗯我想想
链接:https://www.acwing.com/activity/content/code/content/2800726/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

以上是关于PAT 第四讲 排序的主要内容,如果未能解决你的问题,请参考以下文章

如何使用python划分列表并按升序和降序排序?

PAT第四章速刷

数组排序 和 二分法查找

深入JDK源码之Arrays类中的排序查找算法(转)

第第四讲计算机系统结构的发展

第四讲 SVN