sort函数

简介:

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>());  //从大到小排序
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值