#include <vector>
using namespace std;
class minHeap
{
private:
vector<int> array;
int theSize;
public:
minHeap()
{
array = vector<int>(100);
theSize =0;
}
void Insert(int theData);
void Delete(int pos);
void Print();
};
//插入函数,主要是将元素下滚,hole上滚,因为插入的位置是在最后,
//故hole在最后,所以像hole中滚动就是下滚
void minHeap::Insert(int theData){
if(theSize+1>array.size())
array.resize(array.size()*2);
//最后一个元素的下一个位置形成一个hole,以便接受滚下来的元素
int hole = ++theSize;
//hole向前移动的结束条件是hole到头或者hole的父节点元素比要插入的元素小
for(; hole > 1 && array[hole/2] > theData; hole = hole/2)
//hole的父节点元素滚入到hole,hole=hole/2实现了hole滚动到父节点
array[hole]=array[hole/2];
//hole滚动到合适位置了,将要插入的元素填入到hole
}
//删除指定位置元素的函数,该位置以前的位置不动,以后的位置主要是将元素上滚,
//hole下滚,因为删除后是拿最后一个元素来作为删除后剩下的hole的值,
//很大,故hole要下滚
{
//删除的位置大于heap的边界,返回错误
{
cout<<"error!"<<endl;
return;
}
//删除的位置留下一个hole
int hole = pos;
//最后一个元素的值放入到tmp,也就是hole中,准备比较,然后下滚
int tmp = array[theSize--];
//hole还有子节点,也就是hole还有下滚的余地
{
int child;
//hole只有一个子节点,则child只能是这个值
child = hole*2;
//这个if else是拿hole两个子节点中教小的值和hole作比较,
//让较小的值滚上来成为较大值的父节点,
//hole替代较小值的位置
{
child = hole*2+1;
}
else
{
child = hole*2;
}
//较小子节点上滚
array[hole] = array[child];
//hole下滚
}
//hole没有下滚的余地了,将hole中填上滚之前的heap的最后一个元素
}
void minHeap::Print()
{
for(int i=1;i<=theSize;i++)
cout<<array[i]<<endl;
}
int main()
{
minHeap heap;
heap.Insert(7);
heap.Insert(1);
heap.Insert(3);
heap.Insert(4);
heap.Insert(2);
heap.Insert(12);
heap.Insert(10);
heap.Insert(17);
cout<<"**************************"<<endl;
heap.Print();
heap.Delete(2);
cout<<"**************************"<<endl;
heap.Print();
heap.Insert(5);
cout<<"**************************"<<endl;
heap.Print();
return 1;
}
参考自:[数据结构与算法分析–C.描述(第3版)](美)Mark.Allen.Weiss.扫描版(P172)
运行结果如下图: