#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//算法:对vector进行堆(heap)排序
int main() {
int myints[] = { 10, 20, 30, 5, 15 };//整形数组的初始化
vector<int> v(myints, myints + 5);//将整型数组转化成vector
vector<int>::iterator it;
//建堆
make_heap(v.begin(), v.end());//该函数是使用范围内的元素建立成一个堆(默认是大顶堆)。并将堆存放到原来的容器内。
//将范围内的元素建成堆可以快速地取得其范围内的最大值,并且支持快速插入元素。
cout << "initial max heap : " << v.front() << endl;
//移除最大元素
pop_heap(v.begin(), v.end());//取走根节点,因为是max-heap,pop_heap之后,最大元素只是被置于底部容器的最尾端,尚未被取走,且重新调整heap结构。
v.pop_back();//可以高效地移除vector中的最后一个元素。
cout << "max heap after pop : " << v.front() << endl;
for (unsigned i = 0; i<v.size(); i++) cout << " " << v[i];
cout << endl;
//添加元素
v.push_back(99); //vector添加元素
push_heap(v.begin(), v.end());//在堆中添加数据(要先在容器尾端加入数据,再调用push_heap ()),且重新调整heap结构。
cout << "max heap after push: " << v.front() << endl;
for (unsigned i = 0; i<v.size(); i++) cout << " " << v[i];
cout << endl;
//堆排序
sort_heap(v.begin(), v.end());
cout << "final sorted range :";
for (unsigned i = 0; i<v.size(); i++) cout << " " << v[i];
cout << endl;
return 0;
}
c++堆排序
最新推荐文章于 2021-11-08 14:53:21 发布