64,637
社区成员
发帖
与我相关
我的任务
分享
make_heap
while (堆不为空)
pop_heap --》线性表首
用堆排序时,堆的优先级判断逻辑正好与我们排序的代先级逻辑正好相反,这是为了实现“原位转换”的堆排序。我们把表的前一部分组成堆,后一部分组成线性表(最开始时这一部分为空),每次从堆中pop,都会另堆收缩一个元素,空出来的位置正好在线性表的前面,因此我们每次都从堆中取出放在表首而不是表尾,这就要求从堆中取出的是最大值而不是最小值。
#include <iostream> // std::cout
#include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector> // std::vector
int main () {
int myints[] = {3,20,35,5,45};
std::vector<int> v(myints,myints+5);
std::make_heap (v.begin(),v.end());
std::cout << "initial max heap : " << v.front() << '\n';
for (unsigned i=0; i<v.size(); i++)
std::cout << ' ' << v[i];
std::cout << '\n';
std::pop_heap (v.begin(),v.end());
std::cout << "max heap after pop : " << v.front() << '\n';
std::cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
std::cout << ' ' << v[i];
std::cout << '\n';
getchar();
return 0;
}