sort排序的应用
sort函数用于C++中,对给定区间所有元素进行排序,默认为升序,也可进行降序排序。sort函数进行排序的时间复杂度为n*log2n,比冒泡之类的排序算法效率要高,sort函数包含在头文件为#include的c++标准库中。
函数介绍
语法
Sort(start,end,cmp)
参数
(1)start表示要排序数组的起始地址;
(2)end表示数组结束地址的下一位;
(3)cmp用于规定排序的方法,可不填,默认升序。
在使用sort排序时,我们需要灵活设置cmp,以及存储单元。在设置cmp函数时,一定要给函数返回值true或者false
简单数组排序
示例一
sort函数默认从小到大(升序)排列:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={9,6,3,8,5,2,7,4,1,0};
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i];
return 0;
}
输出:0123456789
示例二
通过改变cmp来实现从小到大的排序
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
if (a>b)return 1;
else return 0;
}
int main()
{
int a[10]={9,6,3,8,5,2,7,4,1,0};
sort(a,a+10,cmp);
for(int i=0;i<10;i++) cout<<a[i]<<" ";
return 0;
}
输出:9 8 7 6 5 4 3 2 1 0
字符串数组排序
对于数字位数非常大的数字例如(100位数字),我们使用寻常long,int,long long不一定能够表示,这时候我们可以用字符串数组来存储。
伪代码
#include <bits/stdc++.h>
using namespace std;
bool cmp (string a,string b)
{
return;//排序条件
}
int main()
{
string s[21];
int n;
cin>>n;
for (int i=0;i<n;i++) cin>>s[i];
sort(s,s+n,cmp);
for (int i=0;i<n;i++) cout<<s[i];
return 0;
}
结构体
对于多组的数据,每组中又有多个数据的排序,我们可以采用结构体来存储,利用sort函数排序;
例如我们对一个点集排序
输入
第一行,一个整数n表示点数。
接下来 n 行,三个整数 xi,yi,zi(根据zi的大小按照从小到达的顺序排序)
表示第 ii 个点的坐标。
输入示例
4
2 3 2
1 1000 1
4 893 4
77 3 3
输出
1 1000 1
2 3 2
77 3 3
4 893 4
代码
#include <bits/stdc++.h>
using namespace std;
struct py
{
int x,y,z;
}a[501];
bool cmp (py m,py n)
{
return m.z<n.z;
}
int main()
{
int n;
double ans=0,d,b,c;
cin>>n;
for (int i=0;i<n;i++)
{
cin>>a[i].x>>a[i].y>>a[i].z;
}
sort (a,a+n,cmp);
for (int i=0;i<n;i++)
{
cout<<a[i].x<<" "<<a[i].y<<" "<<a[i].z<<endl;
}
return 0;
}