C++中的排序函数

 

1.sort

头文件:#include <algorithm>

1.1使用sort对数组进行排序

#include<iostream>
#include<algorithm>

int main()
{
    int a[10] = { 9,6,3,8,5,2,7,4,1,0 };
    std::cout << "before sort: " << std::endl;
    for (int i = 0; i<10; i++)
           std::cout << a[i] << " ";
    std::sort(a, a + 10);
    std::cout << std::endl << "after sort: " << std::endl;
    for (int i = 0; i<10; i++)
        std::cout << a[i] << " ";
    return 0;
}

----运行结果: 

before sort:
9 6 3 8 5 2 7 4 1 0
after sort:
0 1 2 3 4 5 6 7 8 9 请按任意键继续. . .

上述做法默认是升序排列,如果想要降序排列,需要自己编写compare函数,作为sort函数的第三个参数传入。

#include<iostream>
#include<algorithm>

bool cmp(const int &a, const int &b)
{
    return a > b;
}

int main()
{
    int a[10] = { 9,6,3,8,5,2,7,4,1,0 };
    std::cout << "before sort: " << std::endl;
    for (int i = 0; i<10; i++)
           std::cout << a[i] << " ";
    std::sort(a, a + 10, cmp);
    std::cout << std::endl << "after sort: " << std::endl;
    for (int i = 0; i<10; i++)
        std::cout << a[i] << " ";
    return 0;
}

----运行结果:

before sort:
9 6 3 8 5 2 7 4 1 0
after sort:
9 8 7 6 5 4 3 2 1 0 请按任意键继续. . .

1.2 使用sort对vector进行排序

用法同1.1类似,只是需要传入vector的迭代器作为参数。

#include <iostream>
#include <algorithm>
#include <vector>

bool cmp(const int &a, const int &b)
{
    return a > b;
}


int main()
{
    std::vector<int> a = { 9,6,3,8,5,2,7,4,1,0 };
    std::cout << "before sort: " << std::endl;
    for (auto i : a)
           std::cout << i << " ";
    std::sort(a.begin(), a.end());
    std::cout << std::endl << "升序排列:" << std::endl;
    for (auto i : a)
        std::cout << i << " ";
    std::cout << std::endl << "降序排列:" << std::endl;
    std::sort(a.begin(), a.end(), cmp);
    for (auto i : a)
        std::cout << i << " ";

    return 0;
}
before sort:
9 6 3 8 5 2 7 4 1 0
升序排列:
0 1 2 3 4 5 6 7 8 9
降序排列:
9 8 7 6 5 4 3 2 1 0 请按任意键继续. . .

若想实现降序排列,也可以用reverse将升序排列好的结果,翻转一下。但这样的效率不高。reverse函数的用法也是类似。

reverse(a.begin(),a.end()); // 翻转vector

 

2.部分排序partial_sort

待更新。。

 

  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值