1.如何使用 sort 排序
sort 函数的使用必须加上头文件 “#include <algorithm>” 和 "using namespace std;"
格式:
sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填));
如果不写比较函数,则默认对前面给出的区间进行递增排序
int 型数组:
int a[6] = {9, 4, 2, 5, 6, -1};
// 将a[0]-a[3]从小到大排序
sort(a, a+4);
for(int i = 0; i < 6; i++){
printf("%d ", a[i]);
}
printf("\n");
// 将a[0]-a[5]从小到大排序
sort(a, a+6);
for(int i = 0; i < 6; i++){
printf("%d ", a[i]);
}
double 型数组:
double a[] = {1.4, -2.1, 9};
sort(a, a+3);
for(int i = 0; i < 3; i++){
printf("%.1f ", a[i]);
}
char 型数组:
char c[] = {'T', 'W', 'A', 'K'};
sort(c, c+4);
for(int i = 0; i < 4; i++){
printf("%c", c[i]);
}
2. 如何实现比较函数 cmp
(1)基本数据类型
#include <cstdio>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
int a[] = {3, 1, 4, 2};
sort(a, a+4, cmp);
for(int i = 0; i < 4; i++){
printf("%d ", a[i]);
}
return 0;
}
(2)结构体数组的排序
一级排序:将 ssd 数组按照 x 从大到小排序
#include <cstdio>
#include <algorithm>
using namespace std;
struct node{
int x, y;
}ssd[10];
bool cmp(node a, node b){
return a.x > b.x;
}
int main(){
ssd[0].x = 2;
ssd[0].y = 2;
ssd[1].x = 1;
ssd[1].y = 3;
ssd[2].x = 3;
ssd[2].y = 1;
sort(ssd, ssd+3, cmp);
for(int i = 0; i < 3; i++){
printf("%d %d\n", ssd[i].x, ssd[i].y);
}
return 0;
}
二级排序:先按 x 从大到小排序,但当 x 相等的情况下,按照 y 的大小从小到大来排序
cmp的写法:
bool cmp(node a, node b){
if(a.x != b.x)
return a.x > b.x;
else
return a.y < b.y;
}
3. 容器的排序
在 STL 标准容器中,只有 vector、string、deque 是可以使用 sort 的。
vector:
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
vector<int> vi;
vi.push_back(3);
vi.push_back(1);
vi.push_back(2);
sort(vi.begin(), vi.end(), cmp);
for(int i = 0; i < 3; i++){
printf("%d ", vi[i]);
}
return 0;
}
string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
string str[3] = {"bbbb", "cc", "aaa"};
sort(str, str+3);
for(int i = 0; i < 3; i++){
cout << str[i] << endl;
}
return 0;
}
排序题型的常用解题步骤
1. 相关结构体的定义
题目会给出个体的许多信息,常常将他们存至一个结构体中,然后用结构体数组来表示多个个体。
2. cmp 函数的编写
对所有学生先按分数从高到低排序,分数相同的按姓名的字典序从小到大排序。——等价表述如下:
① 如果两个学生分数不相同,那么分数高的排在前面;
② 否则,将姓名字典序小的排在前面
bool cmp(Student a, Studeng b){
if(a.score != b.score)
return a.score > b.score;
else
return strcmp(a.name, b.name) < 0;
}
strcmp 函数:
string.h 头文件下用来比较两个 char 型数组的字典序大小的,其中
strcmp(str1, str2)
当 str1 的字典序 小于 str2,返回一个负数;
当 str1 的字典序 等于 str2,返回 0 ;
当 str1 的字典序 大于 str2,返回一个正数。
3. 排名的实现
一般规则:分数不同的排名不同,分数相同的排名相同但占用一个排位
对这种要求,需要在 结构体类型定义 时就把 排名 这一项加到结构体中,方法:
① 先将数组第一个个体(假设数组下标从 0 开始)的排名记为 1,然后遍历剩余个体:如果当前个体的分数等于上一个个体的分数,那么当前个体的排名等于上一个个体的排名,否则,当前个体的排名等于 数组下标 加 1 。
stu[0].r = 1;
for(int i = 1; i < n; i++){
if(stu[i].score == stu[i-1].score)
stu[i].r = str[i-1].r;
else
stu[i].r = i+1;
}
② 有时题目不一定需要把排名记录下来,而是直接输出即可:令 int 型变量 r 初值为 1,然后遍历所有个体:如果当前个体不是第一个个体且当前个体的分数不等于上一个个体的分数,那么令 r 等于数组下标 加 1,这时 r 就是当前个体的排名,直接输出。
int r = 1;
for(int i = 0; i < n; i++){
if(i > 0 && stu[i].score != stu[i-1].score)
r = i+1;
}
——摘抄自《算法笔记》