1.从小到大排序
sort(数组名+n1,数组名+n2);
示例:
#include<iostream>
#include<algorithm>
int main()
{
int a[]={5,9,3,7,5,4,10};
sort(a,a+sizeof(a)/sizeof(int));
for(int i=0;i<sizeof(a)/sizeof(int));i++)
cout<<a[i]<<" ";
return 0;
}
通过改变n1,n2的数值,可以将一个指定区间内的元素进行排序,如:
sort(a+2,a+6);//将数组下标为2到5的元素进行排序;
注意:区间为左闭右开,即数组下标为[2,6),将第3至第6个元素进行排序。
2.从大到小排序
#include<iostream>
#include<algorithm>
int main()
{
int a[5]={2,9,4,6,1};
sort(a,a+5,greater());
for(int i=0;i<5;i++){
cout<<a[i]<<" ";
return 0;
}
3.自定义排序规则,对任意类型T的数组进行排序
#include<iostream>
#include<algorithm>
int main()
{
struct rule
{
bool operator()(const int& a1,const int& a2)const{
return a1%10<a2%10;
}
};
int a[5]={54,12,68,35,42};
sort(a,a+5);
for(int i=0;i<5;i++)
cout<<a[i]<<" ";
return 0;
}
对结构体进行排序
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
struct student
{
char name[20];
int id;
double gpa;
};
student s[]={{"jafs",45,1.6},{"sfjkls",16,3.5},{"fnsf",78,4.9}};
struct rule1
{
bool operator()(const int & a1,const int & a2)const{
return a1%10>a2%10;
}
};
struct rule2
{
bool operator()(const student& s1,const student& s2)const
{
return s1.id<s2.id;
}
};
struct rule3
{
bool operator()(const student& s1,const student& s2)const
{
if(strcmp(s1.name,s2.name)<0)
return true;
return false;
}
};
struct rule4
{
bool operator()(const student& s1,const student& s2)const{
return s1.gpa<s2.gpa;
}
};
sort(s,s+sizeof(s)/sizeof(student),rule3());
for(int i=0;i<sizeof(s)/sizeof(student);i++)
cout<<s[i].name<<" "<<s[i].id<<" "<<s[i].gpa<<endl;
sort(s,s+sizeof(s)/sizeof(student),rule2());
for(int i=0;i<sizeof(s)/sizeof(student);i++)
cout<<s[i].name<<" "<<s[i].id<<" "<<s[i].gpa<<endl;
sort(s,s+sizeof(s)/sizeof(student),rule4());
for(int i=0;i<sizeof(s)/sizeof(student);i++)
cout<<s[i].name<<" "<<s[i].id<<" "<<s[i].gpa<<endl;
return 0;
}