也就是一棵完全二叉树。堆顶最大则为大根堆,堆顶最小则为小根堆,这里实现的是小根堆。
1.定义
用一个数组来存储数据。
typedef int eletype;
typedef struct heapstruct
{
int capacity;
int size;
eletype *arr; //used for saving data
}Heap;
2.新建一个二叉堆
给二叉堆分配空间,给存储数据用的数组分配空间。
Heap *CreateHeap(int max)
{
Heap *H;
H = malloc(sizeof(Heap));
if (H == NULL) {
printf("Out of space\n");
return NULL;
}
H->arr = malloc(sizeof(eletype) * (max + 1));
if (H->arr == NULL) {
printf("Out of space\n");
return NULL;
}
H->capacity = max;
H->size = 0;
H->arr[0] = 0;
return H;
}
3.插入
上滤找到合适的插入位置。
void Insert(Heap *H, eletype data)
{
if (H->size == H->capacity) {
printf("Heap is full\n");
return;
}
int i;
for (i = ++H->size; data < H->arr[i / 2]; i /= 2 )
H->arr[i] = H->arr[i / 2]; //precolate up
H->arr[i] = data;
}
4.删除最小元素(堆顶)
为了保证删除后仍是一个完整的二叉堆,要将原堆顶以下的数据进行适当的上滤。
eletype DeleteMin(Heap *H)
{
if (H->size == 0) {
printf("Heap is empty\n");
return 0;
}
eletype min = H->arr[1];
eletype last = H->arr[H->size--]; //--!
int i, child;
for(i = 1; i * 2 <= H->size; i = child) {
//Find smaller child
child = i * 2;
if (child != H->size && H->arr[child + 1] < H->arr[child])
child++;
//precolate one leve
if (last > H->arr[child])
H->arr[i] = H->arr[child];
else
break;
}
H->arr[i] = last;
return min;
}