The implementation of the heap with the help of the library function vector, for the heap is divided into large piles and small heap, the large heap refers to the root element is greater than the left and right sub-tree elements, conversely, is a small tree. With the example of a large heap, using an array and the following table of the array to represent the number of nodes corresponding to the heap, first, with the last element of the array, relative to the leaf node of the heap, the root node of the leaf node is computed, and then, taking this root node as an example, this subtree will generate a large heap, then find the Until the final root node location is found, the corresponding code is as follows:
At the same time, this example takes advantage of the imitation function, and also can generate a small heap.
Template <class t>
struct less
{
BOOL Operator () (const T &l, const T &s)
{
return L < S;
}
};
Template <class t>
struct Greater
{
BOOL Operator () (const T &l,const t &s)
{
return L >s;
}
};
Template <class T,class com=greater<t>>
Class Heap
{
Protected
Vector<t> _a;
Com _com;
void _creatdown (int parent)
{
int child = 2 * parent + 1;
while (Child < _a.size ())
{
if (Child+1<_a.size () &&_com (_a[child+1], _a[child]))
{
++child;
}
if (_com (_a[child],_a[parent]))
{
Swap (_a[child], _a[parent]);
parent = child;
Child = 2 * parent + 1;
}
Else
{
Break
}
}
}
void _creatup (int child)
{
int parent = (child-1)/2;
while (child>0)
{
if (_com (_a[child], _a[parent]))
{
Swap (_a[child], _a[parent])
Child = parent;
Parent = (child-1)/2;
}
Else
{
Break
}
}
}
Public
Heap ()
{}
Heap (T *a, int size)
{
for (int i = 0; i < size; i++)
{
_a.push_back (A[i]);
}
for (int i = (_a.size ()-2)/2; I >= 0; i--)
_creatdown (i);
}
void push (const T &x)
{
_a.push_back (x);
_creatdown (_a.size ()-1);
}
void print ()
{
for (int i = 0; i < _a.size (); i++)
cout << _a[i]<< "";
}
void Pop ()
{
Swap (_a[0], _a[_a.size ()-1]);
_a.pop_back ();
_creatup (0);
}
};
Implementation of the Heap