您的位置:首页 > 编程语言 > C语言/C++

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

2016-11-25 20:23 260 查看
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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: