C++如何进行sort的使用——C++如何进行排序
简介:
sort()函数,是c++中自带的一个排序方法,它不仅仅是一个简单的快速排序,而是对快速排序的一个优化,它结合了插入排序和堆排序,根据数据量的不同,他会自动选用适合的排序方法。当数据量较大时采用快速排序,分段递归。一旦分段后的数据量小于某个阀值,为避免递归调用带来过大的额外负荷,便会改用插入排序。而如果递归层次过深,有出现最坏情况的倾向,还会改用堆排序。
引用:
sort()函数需要使用#include
代码演示基本使用方法sort()的完整方法是,sort(beg,end,cmd),beg是第一个元素的指针,end是最后一个元素的下一个元素的指针,所以这个sort它是一个左闭右开的,然后这个cmd是一个排序方法,可以不写,如果不写的话默认的是递增排序。
如果想要递减排序的话,需要写这个参数greater
我们演示一下默认的排序方式,与递减的排序方式。
默认排序
在默认方法中,我们可以看见,对于sort方法没有写排序规则cmp。代码语言:javascript代码运行次数:0运行复制#include
#include
using namespace std;
int main(){
int num[10] = {6, 5, 9, 1, 2, 8, 7, 3, 4, 0};
sort(num,num+10);
for(int i = 0;i < 10; i ++)
{
cout << num[i] << " ";
}
// 运行结果
//0 1 2 3 4 5 6 7 8 9
return 0;
} greater
#include
using namespace std;
int main(){
int num[10] = {6, 5, 9, 1, 2, 8, 7, 3, 4, 0};
sort(num, num + 10, greater
for(int i = 0;i < 10; i ++)
{
cout << num[i] << " ";
}
// 运行结果
//9 8 7 6 5 4 3 2 1 0
return 0;
} 自定义规则排序这里我通过一个案例进行讲解。
案例:我们现在希望有一个排序规则,我希望奇数排在偶数前面。
通过这个结果我们发现了,排序结果中奇数在前面偶数在后面,这里主要难写的地方就是这个func函数。
实现代码
代码语言:javascript代码运行次数:0运行复制#include
#include
using namespace std;
bool func(int a, int b)
{
a = a % 2 == 0 ? 1 : 0;
b = b % 2 == 0 ? 1 : 0;
return a < b;
}
int main(){
int num[10] = {6, 5, 9, 1, 2, 8, 7, 3, 4, 0};
sort(num, num + 10, func);
for(int i = 0;i < 10; i ++)
{
cout << num[i] << " ";
}
// 运行结果
//5 9 1 7 3 6 2 8 4 0
return 0;
} 对结构进行排序常见的是对一个学生类进行排序,这个学生类含有的数据类型有,score,num,对成绩相同的,学号小的排在前面。
首先封装一个结构体
代码语言:javascript代码运行次数:0运行复制struct Student{
int num;
int score;
Student() {}
Student(int num,int score):num(num),score(score) {}
};案例的完整代码
代码语言:javascript代码运行次数:0运行复制#include
#include
using namespace std;
struct Student{
int num;
int score;
Student() {}
Student(int num,int score):num(num),score(score) {}
};
bool func(Student x,Student y){
if(x.score == y.score) return x.num < y.num;
return x.score< y.score;
}
int main(){
Student stu[3];
stu[0] = Student(111,100);
stu[1] = Student(110,100);
stu[2] = Student(112,101);
sort(stu,stu+3,func);
for (int i = 0; i < 3; ++ i)
{
cout << "num:" << stu[i].num << " score:" << stu[i].score << endl;
}
return 0;
}运行结果
num:110 score:100
num:111 score:100
num:112 score:101