记录学习
class maxHeap{
public:
int arrLen;//数组长度
int heapSize;//当前长度
int *heap;//方便动态增加数组大小
void initHeap(int *theHeap,int size);
int pop();
void push(const int theElement);
};
void maxHeap::initHeap(int *theHeap,int size){
delete []heap;
heap=theHeap;
heapSize=size;//堆元素个数
//堆化
for(int root=heapSize/2;root>=1;root--){
int rootElement=heap[root];
int child=2*root;
while (child<=heapSize){
if(child<heapSize&&heap[child]<heap[child+1])
child++;//父节点与两孩子较大值比较
if(rootElement>=heap[child])
break;
heap[child/2]=heap[child];
child*=2;//往下移动
}
heap[child/2]=rootElement;
}
}
int maxHeap::pop() {
if(heapSize==0)//空堆
return -1;
int headElement=heap[1];
int lastElement=heap[heapSize--];
int curNode=1;
int child=2;
while (child<=heapSize){
if(child<heapSize&&heap[child]<heap[child+1])
child++;
//比较lastElement和较大孩子的值
if(lastElement>heap[child])
break;
heap[curNode]=heap[child];
curNode=child;//代替child的位置
child*=2;//左孩子的位置
}
heap[curNode]=lastElement;
return headElement;
}
void maxHeap::push(const int theElement) {
if(heapSize==arrLen-1) {//数组已满,扩容
int *newHeap=new int [2*arrLen];
for(int i=1;i<=heapSize;i++)
newHeap[i]=heap[i];
delete []heap;
heap=newHeap;
arrLen*=2;//数组长度变为原来的二倍
}
int curNode=++heapSize;
//从最后一个叶子节点往上移动
while (curNode!=1 && heap[curNode/2]<theElement ){
heap[curNode]=heap[curNode/2];
curNode/=2;
}
heap[curNode]=theElement;
}