#include<stdio.h>
#include<vector>
#include<assert.h>
using namespace std;
template<class T>
struct Less
{
bool operator()(const T&left,const T&right)
{
return left<right;
}
};
template<class T>
struct Greater
{
bool operator()(const T&left,const T&right)
{
return left>right;
}
};
template<class T,class Compare=Less<T>>
class Heap
{
public:
Heap()
{}
Heap(const T* arry,size_t size)
{
_heap.reserve(size);
for(int i=0;i<size;i++)
{
_heap.push_back(arry[i]);
}
int _size=_heap.size();
for(int root=(_size-2)/2;root>=0;--root)
{
AdjustDown(root);
}
}
void Push(const T&value)
{
_heap.push_back(value);
AdjustUp(_heap.size()-1);
}
void Pop()
{
assert(!_heap.empty());
swap(_heap[0],_heap[_heap.size()-1]);
_heap.pop_back();
AdjustDown(0);
}
T& GetTop()
{
assert(!_heap.empty());
return _heap[0];
}
size_t Size()
{
return _heap.size();
}
private:
void AdjustDown(size_t root)
{
assert(!_heap.empty());
int parent=root;
int child=parent*2+1;
int size=_heap.size();
while(child<size)
{
if((child+1<size)&&Compare()(_heap[child],_heap[child+1]))
child=child+1;
if(Compare()(_heap[child],_heap[parent]))
{
swap(_heap[child],_heap[parent]);
parent=child;
child=2*parent+1;
}
else
return;
}
}
void AdjustUp(size_t root)
{
assert(!_heap.empty());
int size=_heap.size();
int child=root;
int parent=(child-1)>>1;
while(parent>0)
{
if(Compare()(_heap[parent],_heap[child]))
{
swap(_heap[parent],_heap[child]);
child=parent;
parent=(child-1)>>1;
}
else
return ;
}
}
vector<T> _heap;
};
void TestHeap()
{
int arry[]={10,11,98,56,16,18,15,17,14,19};
Heap<int> hp1(arry,sizeof(arry)/sizeof(arry[0]));
hp1.Push(34);
hp1.Pop();
}
int main()
{
TestHeap();
system("pause");
return 0;
}
堆的创建
最新推荐文章于 2023-09-12 18:10:25 发布