堆排序——C++关于堆排序的库函数排序

本文介绍了C++标准库中用于实现堆排序的sort_heap函数及其使用方法。通过示例展示了如何利用make_heap和sort_heap对随机生成的整数数组进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++中对于堆排序算法,其实是有一个专门的库函数:sort_heap

 void sort_heap (RandomAccessIterator first, RandomAccessIterator last,Compare comp);

默认make_heap为按升序排序构造

make_heap(v.begin,v.end,greater<int>());//用定义好的函数greater来排降序

sort_heap(v.begin,v.end,greater<int>());

#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
#include <time.h>
#include <stdlib.h>

using namespace std;

int main () {
    srand((unsigned)time(NULL));
    vector<int> v;//将myints复制到v
    for(int i=0;i<10;i++)//随机生成10个数并排序
        v.push_back(rand()%20);
    make_heap (v.begin(),v.end());
    sort_heap (v.begin(),v.end());

    cout << "final sorted range :";
    for (unsigned i=0; i<v.size(); i++)
        cout << ' ' << v[i];

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值