简介:
sort函数的头文件是#include
sort函数默认的排序方式是升序排序,即从小到大。
时间复杂度仅为O( n*log2(n) )。
可自定义compare 函数,自定义排序方式
#include<algorithm>
using namespace std;
int cmp(int x,int y)
{
return x>y;//降序排列
}
int main()
{
int a[5]={1,5,3,4,2};//假设数组a有5个数据
sort(a,a+5,cmp);//实现降序排列
}
1.升序排列
sort(iterator.begin(),iterator.end());
sort(iterator.begin(),iterator.end(),less());
2.降序排列
sort(iterator.begin(),iterator.end(),greater());
3.也可以自定义排序函数
sort(iterator.begin(),iterator.end(),compare comp);
partial_sort()函数,进行部分排序。
1.partial_sort (Iterator first, Iterator middle, Iterator last);
2.partial_sort (Iterator first, Iterator middle, Iterator last, Compare comp);
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n=10;
vector<int> nums(n);
for(int i=0;i<n;++i)
nums[i]=10-i;
partial_sort(nums.begin(),nums.begin()+5,nums.end());
for(int i=0;i<n;++i)
cout<<nums[i]<<" ";
return 0;
}
partial_sort_copy(),对部分元素进行排序,完毕后复制到另一个容器里。
用法:
1.partial_sort_copy (InputIterator first,InputIterator last,outputIterator result_first,outputIterator result_last);
2.partial_sort_copy (InputIterator first,InputIterator last, outputIterator result_first,outputIterator result_last, Compare comp);
(待排序的容器首指针,尾指针,接收元素的容器的首指针,尾指针)
stable_sort(InputIterator first,InputIterator last)
函数进行稳定排序,不改变相等元素的相对位置。
对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;
}
sort(a.begin(), a.end(), less<int>()); //从小到大排序
sort(a.begin(), a.end(), greater<int>()); //从大到小排序