堆
概念:如果有一个关键码的集合K={k0,k1,……kn-1},把它的所有元素按完全二叉树的顺序存储方式存储在一个一维数组中,并满足Ki<=K2*i+1 且 Ki<=K2*i+2(Ki>=K2*i+1 且 Ki>=K2*i+2),i=0,1,2……,则称这个堆为最小堆(最大堆)。
堆的创建及调整
int array[]={23,21,45,64,28}
先以完全二叉树的方式排列:
再根据要求调整,现以小堆示例:
第一次调整: i=(size-2)/2=1
检测以i为跟节点的子树是否满足小堆,如不满足,则调整
调整方法为:取该节点的左右节点中最小的,与根节点比较,若小于根节点,则与根节点交换,完毕之后,i–
第二次 : i=0
root小于min(left,right),交换两个节点,交换节点之后可能导致刚调整过的子树顺序混乱,所以可能要再次调整。
(i–)<0,完成小堆
堆的插入&删除
插入:在堆的最后一个叶子节点后面插入,然后按照要求进行调整。
删除:在最后一个叶子节点后面插入,与堆顶元素交换,然后进行调整。
进行大小堆排序时的代码大致相同,但较为繁琐,所以用模板参数列表来实现
代码如下:
#include<iostream>
using namespace std;
#include<vector>
#include<assert.h>
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 array[],size_t size)
{
_heap.resize(size);
for(size_t i=0; i<size; ++i)
_heap[i]=array[i];
int root=(_heap.size()-2)>>1;
for(root=root;root>=0; --root)
_AdjustDown(root);
}
protected:
void _AdjustDown(size_t parent)
{
size_t size=_heap.size();
size_t child=parent*2+1;
while(child<size)
{
compare com;
if( child+1<size && com(_heap[child+1],_heap[child]))
child+=1;
if(com(_heap[child],_heap[parent]))
{
std::swap(_heap[parent],_heap[child]);
parent=child;
child=parent*2+1;
}
else
return;
}
}
void _AdjustUp()
{
size_t child=_heap.size()-1;
size_t parent=(child-1)>>1;
while(child != 0)
{
if(compare()(_heap[child],_heap[parent]))
{
std::swap(_heap[child],_heap[parent]);
child=parent;
parent=(child-1)>>1;
}
else
return;
}
}
public:
void Insert(const T& data)//插入
{
_heap.push_back(data);
if(_heap.size()>1)
_AdjustUp();
}
void Remove()//删除
{
assert(!Empty());
std::swap(_heap[0],_heap[_heap.size()-1]);
_heap.pop_back();
if(_heap.size()>1)
_AdjustDown(0);
}
size_t Size()const
{
return _heap.size();
}
bool Empty()const
{
return 0 ==_heap.size();
}
const T& Top()const
{
return _heap[0];
}
private:
vector<T> _heap;
};
这样,只要在测试时指明大堆还是小堆,就可以进行排序了。