#include<stdio.h>
#include<stdlib.h>
typedef struct HNode {
int* data;
int Size;
int Capacity;
}Heap;
typedef Heap MaxHeap;
#define MAXDATA 1000
void InitHeap(MaxHeap* &h, int MaxSize)
{
h = (Heap*)malloc(sizeof(Heap));
if (!h)
exit(-1);
h->data = (int*)malloc((MaxSize +1) * sizeof(int));
if (!h->data)
exit(-1);
h->Size = 0;
h->Capacity = MaxSize;
h->data[0] = MAXDATA;
}
bool IsFull(Heap* h)
{
return(h->Capacity == h->Size);
}
bool IsEmpty(Heap* h)
{
return(h->Size == 0);
}
void Inesrt(Heap* &h,int key)
{
int i;
if (IsFull(h))
{
printf("堆已满");
exit(-1);
}
i = ++ h->Size;
for (; h->data[i/2] < key; i/=2)
h->data[i] = h->data[i/2];
h->data[i] = key;
}
//构建最大堆
void CreatMaxHeap(Heap* &h, int p)
{
int parent, child;
int temp;
temp = h->data[p];
for ( parent = p; parent*2 <= h->Size; parent = child)
{
child = p * 2;
if ((child != h->Size) && (h->data[child] < h->data[child + 1]))
{
child++;
}
if (temp > h->data[child])
{
break;
}
else
{
h->data[parent] = h->data[child];
}
}
h->data[parent] = temp;
}
void BuildHeap(Heap* h)
{
int i;
for ( i = h->Size/2; i > 0; i--)
{
CreatMaxHeap(h,i);
}
}
void Delete(Heap* &h)
{
int MaxItem, temp;
int parent, child;
if (IsEmpty(h))
exit(-1);
MaxItem = h->data[1];
temp = h->data[h->Size];
h->Size--;
for (parent = 1; parent * 2 <= h->Size; parent = child)
{
child = parent * 2;
if ((child != h->Size) && (h->data[child] < h->data[child + 1]))
child++;
if (temp > h->data[child])
{
break;
}
else
{
h->data[parent] = h->data[child];
}
}
h->data[parent] = temp;
}
void main()
{
MaxHeap *h;
InitHeap(h,10);
Inesrt(h, 1);
Inesrt(h, 2);
Inesrt(h, 5);
Inesrt(h, 9);
Inesrt(h, 4);
Inesrt(h, 3);
BuildHeap(h);
Delete(h);
for (int i = 1; i <= h->Size; i++)
{
printf("%d\n",h->data[i]);
}
}
堆操作(初始化,插入,删除最大节点,构建最大堆)
最新推荐文章于 2022-06-06 21:03:59 发布