template<typename T>
class Heap
{
public:
Heap(int capacity):size(0)
{
v.resize(1+capacity);
v[0]=0;
}
const T& Top()
{
assert(!IsEmpty());
return v[1];
}
void Push(const T& val)
{
size++;
v[size]=val;
SiftUp(size);
}
void Pop()
{
assert(!IsEmpty());
swap(v[1],v[size]);
size--;
//**************
if (!IsEmpty())
{
SiftDown(1);
}
//**************
}
bool IsEmpty()
{
return size == 0;
}
private:
void SiftUp(int index)
{
assert(index >= 1 && index <= size);
int i=index;
while(i/2 !=0 && Pred(v[i],v[i/2]))
{
assert(i >= 1 && i <= size);
swap(v[i],v[i/2]);
i/=2;
}
}
void SiftDown(int index)
{
assert(index >= 1 && index <= size);
int lchild=2*index;
int rchild=lchild+1;
int i=index;
if (lchild <= size && Pred(v[lchild],v[i]))
{
i=lchild;
}
if (rchild <= size && Pred(v[rchild],v[i]))
{
i=rchild;
}
assert(i >= 1 && i <= size);
if (i != index)
{
swap(v[index],v[i]);
SiftDown(i);
}
}
bool Pred(const T& left,const T& right)
{
return left > right;
}
private:
int size;
//start from 1
vector<T> v;
};
int main ()
{
//
srand(time(0));
//
vector<int> vi;
Heap<int> h(100);
for (int i=0;i<100;i++)
{
int r=rand();
h.Push(r);
cout << r << '/t';
vi.push_back(r);
}
cout << endl;
int v=h.Top();
h.Pop();
while(!h.IsEmpty())
{
cout << v << '/t';
int temp=h.Top();
h.Pop();
assert(temp <= v);
v=temp;
}
cout << v << '/t';
cout << endl;
//
sort(vi.begin(),vi.end(),greater<int>());
for (int i=0;i<vi.size();i++)
{
cout << vi[i] << '/t';
}
//
system("pause");
return 0;
}