1、sort函数的时间复杂度为n*log2(n),执行效率较高。
2、sort函数的形式为sort(first,end,method)//其中第三个参数可选。
3、若为两个参数,则sort的排序默认是从小到大,见如下例子
- #include<iostream>
-
- #include<algorithm>
-
- using namespace std;
-
- int main()
-
- {
-
- int a[10]={9,6,3,8,5,2,7,4,1,0};
-
- for(int i=0;i<10;i++)
-
- cout<<a[i]<<endl;
-
- sort(a,a+10);
-
- for(int i=0;i<10;i++)
-
- cout<<a[i]<<endl;
-
- return 0;
-
- }
4、若为三个参数,则需要写一个cmp函数(此名称cmp可变),用于判断是从小到大排序还是从大到小排序。
(1)需要排序的数组直接为int类型,则见如下例子(从大到小排序)
- #include <algorithm>
- #include <iostream>
- using namespace std;
-
- bool com(int a,int b)
-
- {
-
- return a>b;
-
- }
-
- int main()
-
- {
-
- int a[10]={9,6,3,8,5,2,7,4,1,0};
-
- for(int i=0;i<10;i++)
-
- cout<<a[i]<<endl;
-
- sort(a,a+10,com);
-
- for(int i=0;i<10;i++)
-
- cout<<a[i]<<endl;
-
- return 0;
-
- }
(2)如果想依照一个结构体内的一个int型的属性参数进行排序,则见如下例子(从大到小排列)
- #include <iostream>
- #include <algorithm>
-
- using namespace std;
-
- struct node {
- int a;
-
-
- };
-
- bool cmp(node x,node y)
- {
- if(x.a != y.a)
- return (x.a > y.a);
- }
-
- void main(void)
- {
- int i;
- node N_t[5];
- for(i=0; i<5; i++)
- {
- cin>>N_t[i].a;
- }
- sort(N_t, N_t+5, cmp);
- for(i=0; i<5; i++)
- {
- cout<<N_t[i].a;
- }
-
- }