目录
一、堆整体结构:
#include<iostream>
#include<vector>
#define Size long long
using namespace std;
template<typename P>
class heap{
private:
Size heap_size;//容量限制
Size heap_count;//数据计数
vector<P> heap_elem;//堆容器
int maxmin_heap;//选择大\小根堆
void Up_adjust(int now);//上浮调整
void Down_adjust(P &top, int now);//下沉调整
public:
enum{max_heap=1, min_heap=-1};
heap(Size s, int m=max_heap)://构造堆
heap_size(s){
heap_count=0;
heap_elem.push_back(-999);
maxmin_heap=m;//default max_heap
};
heap(vector<P> lists, int m=max_heap){
heap_size = lists.size()+1;
heap_elem.push_back(-999);
maxmin_heap=m;
heap_count=0;
for(auto e : lists){
push(e);
}
}
P getTop(){//弹获取堆顶元素
if(heap_count>0)return heap_elem[1];
return heap_elem[0]*maxmin_heap;
}
bool empty(){//判断堆空
if(heap_count==0)return true;
return false;
}
void push(P x);//送元素入堆
P pop();//堆顶元素弹出
void Delete(int i);//删除第i个元素
void data();//打印堆
};
二、相关成员函数实现:
1.向堆加入元素
template<typename P>
void heap<P>::push(P x){
++heap_count;
heap_elem.push_back(x*maxmin_heap);
int now=heap_count;
Up_adjust(now);
if(heap_count>heap_size-1)
heap_count--;
}
2.弹出堆顶元素
template<typename P>
P heap<P>::pop(){
P res=getTop()*maxmin_heap;
P top=heap_elem[heap_count--];
int now=1;
Down_adjust(top, now);
heap_elem.pop_back();
cout << "pop "<< res <<" successfully." << endl;
return res;
}
3.删除元素
template<typename P>
void heap<P>::Delete(int i){
if(i>heap_count) return;
cout << "delete heap["<< i <<"]: " << heap_elem[i] << endl;
if(i==heap_count){
heap_count--;
heap_elem.pop_back();
return ;}
Down_adjust(heap_elem[heap_count],i);
heap_count--;
heap_elem.pop_back();
}
4,上浮调整
template<typename P>
void heap<P>::Up_adjust(int now){
while(now>1 && heap_elem[now]>heap_elem[now/2]){
std::swap(heap_elem[now], heap_elem[now/2]);
now=now/2;
}
}
5.下沉调整
template<typename P>
void heap<P>::Down_adjust(P &top, int now){
heap_elem[now]=top;
int next1,next2;
while(now*2<=heap_count){
if(now*2+1>heap_count){
next1=next2=now*2;
}
else{
next1 = heap_elem[now*2]>heap_elem[now*2+1] ? now*2 : now*2+1;
next2 = heap_elem[now*2]<heap_elem[now*2+1] ? now*2 : now*2+1;
}
if(heap_elem[next1]>heap_elem[now]){
swap(heap_elem[next1],heap_elem[now]);
now = next1;
}
else if(heap_elem[next2]>heap_elem[now]){
swap(heap_elem[next2],heap_elem[now]);
now = next2;
}
else{
break;
}
}
}
6.打印堆
template<typename P>
void heap<P>::data(){
typename std::vector<P>::iterator itr=heap_elem.begin()+1;
cout << "heap[]: " ;
for(int i=0;i<heap_count;++i){
cout << *(itr+i)*maxmin_heap << ' ';
}
cout << endl;
}
三、测试代码
int main(){
heap<int> h(10,heap<int>::max_heap);//可更改为min_heap,来构建小根堆
int x;
for(int i=0;i < 10;++i){
x = rand()%100;
h.push(x);
}
h.data();
h.Delete(2);
while(!h.empty()){
h.pop();
}
cout << endl;
return 0;
}
四、测试结果:
大根堆:
小根堆:
五、功能总结:
1.支持获取一个数组的最大的n个元素或者最小的n个元素的查找
2.支持数组排序,只需要建立堆,并插入所有元素,并依次从顶取出即可
3.支持大根堆与小根堆
4.在已满足拷贝构造函数与运算符重载情况下,元素支持自定义对象