数据结构与算法分析,C语言版(第140-141页)中构建堆,原理不再赘叙。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>
typedef int ElementType;
typedef struct HeapStruct *PriorityQueue;
struct HeapStruct {
int Capacity;
int Size;
ElementType *elements;
};
PriorityQueue Initialize(int MaxElements)
{
struct HeapStruct *H;
H = (struct HeapStruct *)malloc(sizeof(struct HeapStruct));
H->elements = (ElementType *)malloc(sizeof(ElementType)*(MaxElements+1));
H->elements[0] = NULL;
H->Capacity = MaxElements;
H->Size = 0;
return H;
}
//二叉堆的高度
int TreeHeight(PriorityQueue p)
{
int size = p->Size;
float height = (int)(log(float(size + 1))/log((float)2));
int _height = ceil(height);
return height;
}
//下滤
void PercolateDown(PriorityQueue p, int index)
{
int child;
for (int i = index; i <= p->Size; i = child)
{
child = i * 2;
if (child <= p->Size && (child + 1) <= p->Size&&p->elements[child] > p->elements[child + 1])
child++;
if (child <= p->Size&&p->elements[child] < p->elements[i])
{
ElementType temp = p->elements[i];
p->elements[i] = p->elements[child];
p->elements[child] = temp;
}
}
}
//构建堆
void BuildHead(PriorityQueue p)
{
int height = TreeHeight(p);
if (height == 1) return;
for (int i = (int)pow((float)2, height - 1)-1; i > 0; i--)
{
PercolateDown(p, i);
}
}
//数据顺序插入到堆中
void InsertHeap(PriorityQueue p, ElementType data)
{
if (p->Capacity != p->Size)
{
p->Size++;
p->elements[p->Size] = data;
}
}
void main()
{
//int a[] = { 10, 12, 1, 14, 6, 5, 8, 15, 3, 9, 7, 4, 11, 13, 2 };
int a[] = { 150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120};
PriorityQueue p = Initialize(sizeof(a)/sizeof(int));
int arraySize = sizeof(a) / sizeof(int);
for (int i = 0; i < arraySize; i++)
{
InsertHeap(p, a[i]);
}
BuildHead(p);
for (int i = 1; i <=p->Size; i++)
{
printf("第%d个元素为:%d\n", i, p->elements[i]);
}
system("pause");