//创建一个堆
void CreatHeap(Heap *hp, int *array, int size)
{
int i = 0; //初始化Heap
hp->_array= (int *)(sizeof (int)*size);
if (hp->_array== NULL)
{
assert(0);
return;
}
hp->_capacity= size; //搬移
for (i; i< size; ++size)
{
hp->_array[i]= array[i];
}
hp->_size= size;
//找数的倒数第一个非叶子结点
int last =((size - 2)>> 1); //最后一个结点是size-1,双亲就是再减一除以2
for (; last>= 0; last--)
{
AdjustDown(hp->_array,hp->_size,last);
}
}
int main()
{
Heap hp;
int a[] = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37 };
CreatHeap(&hp,a,sizeof (a)/sizeof(a[0]));
DestroHeap(&hp);
return 0;
}
//销毁堆
void DestroHeap(Heap *hp)
{
assaer(hp);
free(hp->_array);
hp->_size= 0;
hp->_capacity= NULL;
}
AdjustUp(int *array,int size,int child)
{
int parent= ((child - 1)>> 1);
while (child!=0)
{
if (array[child] < array[parent])
{
Swap(&array[child], &array[parent]);
child =parent;
parent = ((child - 1)>> 1);
}
else
return;
}
}
//插入一个元素
void InsertHeap(Heap *hp, int data)
{
hp->_array[hp->_size++]=data;
AdjustUp(hp->_array,hp->_size,hp->_size- 1);
}
//删除一个元素
void EraseHeap(Heap *hp)
{
//和插入一个元素操作相同
}
//堆里面有效元素的个数
int SizeHeap(Heap *hp)
{
assert(hp);
return hp->_size;
}
//检查堆是否为空
int EmptyHeap(Heap *hp)
{
return 0 == hp->_size;
}
//获取堆顶元素
int TopHeap(Heap *hp)
{
assers(hp);
return hp->_array[0];
}
//检查是否进行扩容
void CheckCapacity(Heap *hp)
{
assert(hp);
if (hp->_size== hp->_capacity)
{
//申请新空间
intnewcapacity = (hp->_capacity)*2;
int *pTemp= (int*)malloc(sizeof(int)*newcapacity);
if (pTemp== NULL)
{
assert(pTemp);
return;
}
//搬元素
for (int i = 0;i < hp->_size;i++)
{
pTemp[i] = hp->_array[i];
}
//释放旧空间
free(hp->_array);
hp->_array= pTemp;
hp->_capacity= newcapacity;
}
}
堆的创建及基础操作
最新推荐文章于 2023-09-12 18:10:25 发布