做项目的时候,排序是一种经常要用到的操作。如果每次都自己写个冒泡之类的O(n^2)排序,不但程序容易超时,而且浪费宝贵的时间,还很有可能写错。STL里面有个sort函数,可以直接对数组排序,复杂度为n*log2(n)。
Sort函数有三个参数:
(1)第一个是要排序的数组的起始地址。
(2)第二个是结束的地址(最后一位要排序的地址)
(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。
一、一维数组排序
如:sort(a,a+n) 表示对a[0] a[1] a[2] ... a[n-1] 排序,sort(a+1,a+n+1) 表示对 a[1] a[2] ... a[n] 排序,sort()排序范围是,第二个参数减第一个参数的差。
下面就具体使用sort()函数结合对数组里的从a[0]开始的十个数进行排序做一个说明!
例一:sort函数没有第三个参数,实现的是从小到大
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main()
{ int a[]={9,6,3,8,5,2,7,4,1,0};
for(int i=0;i<10;i++)
cout<<a[i];
cout<<endl;
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i];
return 0;
}
例二、从a[1]开始的排序。
#include<bits/stdc++.h>
using namespace std;
int main() {
int n,a[1001];
scanf("%d",&n); //输入有多少个数
for (int i = 1;i <= n;i++) scanf("%d",&a[i]); //输入这个数列
sort(a+1,a+n+1); //对a[1] a[2] a[3] ... a[n] 排序
for (int i = 1;i <= n;i++) printf("%d",a[i]); //输出
return 0;
}
省略第三个参数情况下默认升序排序,如果要实现从大到小的降序排序,我们就要用到第三个参数,下面举例说明。
#include<bits/stdc++.h>
using namespace std;
bool cmmp(int a,int b)//函数名由自己定义;
{ return a > b;}
int main()
{ int a[]={9,6,3,8,5,2,7,4,1,0};
for(int i=0;i<10;i++)
cout<<a[i];
cout<<endl;
sort(a,a+10,cmmp);
for(int i=0;i<10;i++)
cout<<a[i];
return 0;
}
这个就是降序排序的比较函数,意思是当a > b时为true,就不交换,a < b时为false,交换。然后我们调用sort(a+1,a+n+1,cmmp);就可以对a[1] a[2] a[3] ... a[n] 进行排序了
二、sort也能对结构体排序:
假设自己定义了一个结构体node
struct node
{ int a;
int b;
double c;
}
有一个node类型的数组node x[1001],想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:
#include<bits/stdc++.h>
using namespace std;
struct node
{ int a,b;double c;}x[1001];
bool cmp(node n,node m)
{if(n.a!=m.a) return n.a<m.a;//如果a.x不等于b.x,就按x从小到大排
if(n.b!=m.b) return n.b>m.b;//如果x相等按y从小到大排
return n.c>m.c;
}
int n;
int main()
{ scanf("%d",&n);
for (int i = 1;i <= n;i++) scanf("%d%d%lf", &x[i].a,&x[i].b,&x[i].c);
sort(x+1,x+n+1,cmp);
for (int i = 1;i <= n;i++) printf("%d %d %lf\n",x[i].a,x[i].b,&x[i].c);
return 0;
}
三、sort也能对string排序:.
- 一个字符串间的个字符排序:使用迭代器可以完成顺序排序
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string str("hello world");
sort(str.begin(),str.end());
cout<<str;
return 0;
}