堆
逻辑:完全二叉树
物理:数组
特性:任意一个节点的值都需大于等于(或小于等于)他的孩子。
堆的基本功能:找最大(最小)值;
建堆
//小堆
void heapify(int a[],int size, int index){
while(1)
{int left= 2index+1;
int right=2index+2;
if(left>=size){
return ;
}
int min=left;
if(right<size&&a[right]<a[left]){
min =right;
}
if(a[index]<=a[min]){
return;
}
int t=a[min];
a[min]=a[index];
a[index]=t;
index=min;
}
}
void createHeap(int a[],int size)
{
for (int i=(size -2)/2;i>=0;i–){
heapify(a,size,i);
}
}
void createHeap(int a[],int size)
{
for (int i=(size -2)/2;i>=0;i–){
heapify(a,size,i);
}
}
void createHeap(int a[], int size) {
for ((size - 1 - 1) / 2; i >= 0; i–) {
heapify(a, size, i);
}
}
typedef struct Heap {
int array[100];
int size;
} Heap;
//堆顶元素
void HeapInit(Heap *heap, int a[], int size) {
for (int i = 0; i < size; i++) {
heap->array[i] = a[i];
}
heap->size = size;
createHeap(heap->array, heap->size);
}
//向上调整
void adjustUp(int a[], int index) {
while (index > 0) {
if (index == 0) {
return;
}
int parent = (index - 1) / 2;
if (a[parent] <= a[index]) {
return;
}
int t = a[parent];
a[parent] = a[index];
a[index] = t;
index = parent;
}
}
//删除堆顶元素
void HeapPush(Heap *heap, int val) {
heap->array[heap->size++] = val;
adjustUp(heap->array, heap->size - 1);
}
void HeapPop(Heap *heap) {
assert(heap->size > 0);
heap->arrray[0] = heap->array[heap->size - 1];
heap->size–;
heapify(heap->array, heap->size, 0);
}
int HeapTop(Heap *heap) {
assert(heap->size > 0);
return heap->array[0];
}