堆操作(初始化,插入,删除最大节点,构建最大堆)

#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]);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鄢广杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值