sort是STL中的排序函数,总结几点用法;
用法一
- 对基本数据类型数组从小到大排序
sort(数组名+n1,数组名+n2);//[n1,n2)
- n1和n2都是int类型的表达式,可以包含变量
- 如果n1=0,则+n1可以不写
例:
#include<iostream>
#include<algorithm>
using namespace std;
int q[]={15,4,3,9,7,2,6};
int main()
{
sort(q,q+7);//将整个数组从小到大排序
for(int i=0;i<7;i++)
printf("%d ",q[i]);
return 0;
}
结果:
用法2
- 对基本数据类型数组从大到小排序
sort(数组名+n1,数组名+n2,greater<T>()); -//[n1,n2)
- T为数据类型例Int,double…
例:
#include<iostream>
#include<algorithm>
using namespace std;
int q[]={15,4,3,9,7,2,6};
int main()
{
sort(q,q+7,greater<int>());//将整个数组从大到小排序
for(int i=0;i<7;i++)
printf("%d ",q[i]);
return 0;
}
结果:
用法3
自定义排序规则,对任何数据类型T的数组排序;
这里有多种写法:
写法1
sort(数组名+n1,数组名+n2,排序规则结构名());
- 定义方式:
struct 结构名
{
bool operator()(const T &a,const T &b)
{
//若a在b前面,则返回true
//否则返回false
}
};
例1自定义对基本数据类型:
#include<iostream>
#include<algorithm>
using namespace std;
int q[]={15,4,3,9,7,2,6};
struct rule
{
bool operator()(const int &a,const int &b)
{
return a>b;//从大到小排
}
};
int main()
{
sort(q,q+7,rule());//将整个数组从大到小排序
for(int i=0;i<7;i++)
printf("%d ",q[i]);
return 0;
}
例2对结构数组进行排序:
#include<iostream>
#include<algorithm>
using namespace std;
int q[]={15,4,3,9,7,2,6};
struct student
{
int id;
double score;
};
struct rule
{
bool operator()(const student &a,const student &b)
{
return a.id>b.id;//id从大到小排
}
};
int main()
{
student stu [] ={{111,66.6},{117,88.8},{101,59.6}};
sort(stu,stu+3,rule());
for(int i=0;i<3;i++)
{
printf("%d %.2lf\n",stu[i].id,stu[i].score);
}
return 0;
//结果
/*
117 88.80
111 66.60
101 59.60
*/
}
写法2
自己写一个函数
sort(数组名+n1,数组名+n2,cmp)
//cmp是个函数名,可以取其他名字,无所谓的
例1对基本数据类型:
#include<iostream>
#include<algorithm>
using namespace std;
int q[]={15,4,3,9,7,2,6};
bool cmp(int a,int b)
{
return a>b;//从大到小
}
int main()
{
sort(q,q+7,cmp);//从大到小排
for(int i=0;i<7;i++)
{
printf("%d ",q[i]);
}
return 0;
}
例2对结构数组进行排序:
#include<iostream>
#include<algorithm>
using namespace std;
struct student
{
int id;
double score;
};
bool cmp(student a,student b)
{
return a.score>b.score; //按score从大到小
}
int main()
{
student stu [] ={{117,66.6},{111,88.8},{101,59.6}};
sort(stu,stu+3,cmp);//按score从小到大排
for(int i=0;i<3;i++)
{
printf("%d %.2lf\n",stu[i].id,stu[i].score);
}
return 0;
//结果
/*
111 88.80
117 66.60
101 59.60
*/
}
比如我们在比较成绩时,如果成绩相同则按学号从小到大排序,可以按照上面的方法这样写
#include<iostream>
#include<algorithm>
using namespace std;
struct student
{
int id;
double score;
};
bool cmp(student a,student b)
{
if(a.score!=b.score)
return a.score>a.score; //先按分数从大到小排
else a.id<b.id; //分数相同按id从小到大
}
int main()
{
student stu [] ={{117,66.6},{111,66.6},{101,59.6}};
sort(stu,stu+3,cmp);
for(int i=0;i<3;i++)
{
printf("%d %.2lf\n",stu[i].id,stu[i].score);
}
return 0;
//结果
/*
111 66.60
117 66.60
101 59.60
*/
}
还有一种写法是重载<
运算符,这个是c++的,这方面的知识不是很了解,我感觉上面的够用了;
总结:
1,sort函数排序时间复杂度是:nlogn;
2,上面写的方法中,如果题目不是从小到大排序的话,当需要按其他规则排序时,我更喜欢用自己定义函数来定义规则,即上面的写法2,感觉好理解,也好记忆一点;
3,sizeof(arr)/sizeof(int)
,这个可以求数组元素个数,int是元素类型,这个类型是根据实际来写;