堆的基本实现

堆的定义:
将元素按照完全二叉树的顺序存储方式存储在一个一维数组中,使之满足ki<=k2i+1 并且ki<=k2i+2(若相反则称为小堆(大小堆的判定看根节点))
堆的性质:
堆中某个节点的值总是不大于或者小于节点
堆是一颗完全二叉树
在这里插入图片描述
代码实现:
c++

#include "Heap.h"
void Swap(HPDataType*x1, HPDataType*x2)
{
	HPDataType x = *x1;
	*x1 = *x2;
	*x2 = x;
}
void AdjustDown(HPDataType*a, int root)
{
	int parent = root;
	int child = parent * 2 + 1;
	while (child < n)
	{
		if ((child + 1 < n) && a[child + 1] > a[child])
		{
			++child;
		}
		if (a[child]>a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void AdjustUp(HPDataType *a, int n, int child)
{
	int parent;
	assert(a);
	parent(child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[parent], &a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapInit(Heap *hp, HPDataType*a, int n)
{
	int i;
	asser(hp&&a);
	hp ->_a = (HPDataType*)malloc(sizeof(HPDataType)*n);
	hp ->_size = n;
	hp ->_capacity = n;
	for (i = 0; i < n; ++i)
	{
		hp->_a[i] = a[i];
	}
}
for (i = (n - 2) / 2; i >= 0; --i)
{
	{
		AdjustDown(hp->_a, hp->_size, i);
	}
}
void HeapDestory(Heap*hp)
{
	assert(hp);
	free(hp->_a);
	hp->_a = NULL;
	hp->_size = hp->_capacity = 0;
}
void HeapPush(Heap*hp, HPDataType x)
{
	assert(hp);
	if (hp->_size == hp->_capacity)
	{
		hp->_capacity *= 2;
		hp->_a = (HPDataType*)realloc(hp->_a, sizeof(HPDataType)*hp->_capacity);
	}
	hp->_a[hp->_size] = x;
	hp->_size++;
	AdjustUp(hp->_a, hp->_size, hp->_size - 1);
}
void HeapPop(Heap*hp)
{
	assert(hp);
	Swap(&hp->_a[0], &hp->_a[hp->_size - 1]);
	hp->_size--;
	AdustDown(hp->_a, hp->_size, 0);
}
HPDataType HeapTop(Heap * hp)
{
	assert(hp);
	return hp->_a[0];
}
int HeapSize(Heap * hp)
{
	assert(hp);
	return hp->_a[0];
}
int HeapSize(Heap*hp)
{
	assert(hp);
	return hp->_a[0];
}
int HeapSize(Heap*hp)
{
	return hp->_size 
}
int HeapEmpty(Heap *hp)
{
	return hp->_size == 0 ? 0 : 1;
}
void HeapPrint(Heap *hp)
{
	int i;
	for (i = 0; i < hp->_size; ++i)
	{
		printf("%d", hp->_a[i]);
	}
	printf("\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值