堆是一个完全二叉树,可以简单的由数组表达出来.
最大堆有如下性质:
父节点总是大于儿子
由于C中数组总是从0开始,为了使得编码简便,我们总是多申请一个头部,赋值为-1
下面是保持堆性质的代码
int left(int index){
int l = index * 2;
return l;
}
int right(int index){
int r = index * 2 + 1;
return r;
}
void swap(int &a,int &b){
int temp = a;
a = b;
b = temp;
}
void max_heapify(int *heap, int index, int heap_size){
int l = left(index);
int r = right(index);
int size = heap_size;
int largest = -1;
if (heap_size >= l&&heap[l] > heap[index])
largest = l;
else
largest = index;
if (r<=heap_size&&heap[r]>heap[largest])
largest = r;
if (largest != index){
swap(heap[index], heap[largest]);
max_heapify(heap, largest, size);
flag++;
}
}