1. 使用sort函数进行默认的从小到大排序
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序
int main()
{
//1. 对int型数组排序
int a[]={4,8,6,2,3,9};
for(int i=0;i<6;i++) //输出原本顺序
cout<<a[i]<<" ";
cout<<endl;
sort(a,a+5); //对a[0]~a[4]进行排序
for(int i=0;i<6;i++)
cout<<a[i]<<" ";
cout<<endl;
//2. 对浮点数数组排序
float b[]={9.1,3.33,-0.2};
sort(b,b+3);
for(int i=0;i<3;i++)
cout<<b[i]<<" ";
cout<<endl;
//3. 对字符型数组排序(默认字典序)
char c[]={'f','a','r','g'};
sort(c,c+4);
for(int i=0;i<4;i++)
cout<<c[i]<<" ";
cout<<endl;
return 0;
}
2. 使用sort函数进行从大到小排序
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
//4. 使用cmp()比较函数进行自定义规则排序
//(1)对int型进行从大到小排序
int A[]={4,7,6,9,2,-1};
sort(A,A+6,cmp);
for(int i=0;i<6;i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
3. 使用sort函数对结构体数组进行自定义排序
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序
struct Node
{
int x,y;
}nodes[3];
bool cmp(Node a,Node b)
{
return a.x>b.x;
}
int main()
{
//(2)对结构体数组进行排序
//Node nodes[3];
nodes[0].x=2; //(2,2)
nodes[0].y=2;
nodes[1].x=3; //(3,5)
nodes[1].y=5;
nodes[2].x=1; //(1,3)
nodes[2].y=3;
sort(nodes,nodes+3,cmp); //按x从大到小排序
for(int i=0;i<3;i++)
cout<<"("<<nodes[i].x<<","<<nodes[i].y<<") ";
cout<<endl;
return 0;
}