函数原型:
void sort (first, last, com);
使用快速排序实现
- first 是要排序的数组的起始地址。
- last 是结束的地址(最后一个元素的下一个元素地址) 区间为 [first, last)
- com 是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。
- 在使用时必须包含头文件
algorithm
且必须使用using namespace std
;
常规使用
#include<cstdio>
#include<algorithm>
using namespace std;
int main() {
int a[10] = {5, 3, 2, 5, 7, 8, 3, 1, 9, 2};
sort(a, a + 10);
for(int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
return 0;
}
比较函数 cmp 的使用
一般用法:
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b; //表示将a放在前面,即大的在前
}
int main() {
int a[10] = {5, 3, 2, 5, 7, 8, 3, 1, 9, 2};
sort(a, a + 10, cmp);
for(int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
return 0;
}
在结构体中的使用:
#include<cstdio>
#include<algorithm>
using namespace std;
struct node {
int x, y;
};
bool cmp(node a, node b) {
return a.x > b.x;
}
int main() {
struct node n[3];
n[0].x = 1, n[0].y = 3;
n[1].x = 3, n[1].y = 1;
n[2].x = 2, n[2].y = 4;
sort(n, n + 3, cmp);
for(int i = 0; i < 3; i++) {
printf("x = %d, y = %d\n", n[i].x, n[i].y);
}
return 0;
}
/*
x = 3, y = 1
x = 2, y = 4
x = 1, y = 3
*/
一个实例
根据学生的分数给出其排名。
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
struct Student {
char name[10]; //姓名
int score; //成绩
int r; //排名
} stu[10];
bool cmp(Student s1, Student s2) {
if(s1.score != s2.score) {
return s1.score > s2.score;
} else {
return strcmp(s1.name, s2.name) < 0;
}
}
int main() {
strcpy(stu[0].name, "a"), stu[0].score = 90;
strcpy(stu[1].name, "b"), stu[1].score = 89;
strcpy(stu[2].name, "c"), stu[2].score = 91;
strcpy(stu[3].name, "d"), stu[3].score = 90;
sort(stu, stu + 4, cmp);
stu[0].r = 1;
for(int i = 1; i < 4; i++) {
if(stu[i].score == stu[i - 1].score) {
stu[i].r = stu[i - 1].r;
} else {
stu[i].r = stu[i - 1].r + 1;
}
}
for(int i = 0; i < 4; i++) {
printf("%s %d %d\n", stu[i].name, stu[i].score, stu[i].r);
}
}
/*
c 91 1
a 90 2
d 90 2
b 89 3
*/