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;
}