1. 普通排序:升序
sort() 区间:[ , )
int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a,a+10); //2 3 4 5 5 6 6 8 9 100
可以对数组中任意一段排序
int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a+2,a+5);//2 5 6 8 9 4 3 5 6 100
2. 降序
(1)greater 参数
int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a,a+10,greater<int>()); //100 9 8 6 6 5 5 4 3 2
//greater< >() 尖括号里面的数据类型可以改 但是形式必须一样
(2)struct -bool 式 即自定义排序类型, 非常灵活,不仅可以写降序,想什么顺序就什么顺序。
形式如下:
struct *rule1* //除了* *中的可变,其余部分照抄 a1,a2 不建议变更就是一个参数
{
bool operator()(const *int* &*a1*,const *int* &*a2*) //int 可变更 ,是数据类型
{
*return a1>a2;* //这一部分阐释按什么规则排序 现在这个就是按降序
}
};
3.结构体排序
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
struct student{
int a;
char b[50];
double c;
} STU[]={{5,"asef",500},{6,"gdfg",10.5},{50,"rth",20.3},{30,"trh",10.8}};
struct rule1 //规则一:按结构体中的a的降序 排结构体数组
{
bool operator()(const student &a1,const student &a2)
{
return a1.a>a2.a;
}
};
struct rule2{ //规则二:按结构体中的c的降序 排结构体数组
bool operator()(const student &a1,const student &a2)
{
return a1.c>a2.c;
};
};
struct rule3 //规则三:按结构体中的b的降序 排结构体数组
{
bool operator() ( const student &a1,const student &a2)
{
if(stricmp(a1.b,a2.b)>0) //stricmp() 比较两个字符串s1 s2,if(s1>s2) 返回>0
// if(s1<s2) 返回<0
// if(s1=s2) 返回=0
return true;
else
return false;
};
};
void PRINT(student STU[],int n)
{
for(int i=0;i<4;i++)
{
printf("%d %s %lf ",STU[i].a,STU[i].b,STU[i].c);
}
cout<<endl;
}
int main()
{
sort(STU,STU+5,rule1()); PRINT(STU,1);
sort(STU,STU+5,rule2()); PRINT(STU,1);
sort(STU,STU+5,rule3()); PRINT(STU,1);
return 0;
}
/*
4672992 0.000000 50 rth 20.300000 30 trh 10.800000 6 gdfg 10.500000
5 asef 500.000000 50 rth 20.300000 30 trh 10.800000 6 gdfg 10.500000
30 trh 10.800000 50 rth 20.300000 6 gdfg 10.500000 5 asef 500.000000
*