堆的实现
class Heap {
private:
int *data, size;
public:
Heap(int length_input) {
data = new int[length_input];
size = 0;
}
~Heap() {
delete[] data;
}
void push(int value){
}
};
此处实现一个大根堆,根节点的值最大
堆的插入
具体原理略
void push(int value) {
data[size] = value;
int current = size;
int father = (current - 1) / 2;
while (data[current] > data[father]) {
swap(data[current], data[father]);
current = father;
father = (current - 1) / 2;
}
size++;
}
堆的删除与上滤
首先找出当前最大的值——确认其是自身,左孩子还是右孩子
然后进行交换
再从交换后的节点出发,递归调用
void update(int pos,int n){
int lchild=2*pos+1,rchild=2*pos+2;
int max_value=pos;
if(lchild<n&&data[lchild]>data[max_value]){
max_value=lchild;
}
if(rchild<n&&data[rchild]>data[max_value]){
max_value=rchild;
}
if(max_value!=pos){
swap(data[pos],data[max_value]);
update(max_value,n);
}
}
void pop(){
swap(data[0],data[size-1]);
size--;
update(0,size);
}
网友评论