#pragma once
#include<malloc.h>
#include<assert.h>
typedef int HeapDateType;
typedef struct Heap
{
HeapDateType* _a;
size_t _size;
size_t _capacity;
}Heap;
void HeapInit(Heap* hp, HeapDateType* a, size_t n);//创建堆
void HeapMake(Heap* hp);//建大小堆
void HeapPush(Heap* hp, HeapDateType x);//进堆
void HeapPop(Heap* hp);//删除堆顶
size_t HeapSize(Heap* hp);//堆大小
size_t HeapEmpty(Heap* hp);//对是否为空
HeapDateType HeapTop(Heap* hp);//访问堆顶
void HeapSort(Heap* hp);//堆排序
void HeapAdjustDown(Heap* hp, int root);//向下调整
void HeapAdjustUp(Heap* hp, int child);//向上调整
void Swap(HeapDateType* a, HeapDateType* b);//交换
void Print(Heap* hp);//打印堆
void HeapInit(Heap* hp, HeapDateType* a, size_t n)
{
hp->_a = (HeapDateType*)malloc(sizeof(HeapDateType)*n);
assert(hp->_a);
hp->_size = 0;
hp->_capacity = n;
for (size_t i = 0;i < n;i++)
{
hp->_a[hp->_size] = a[hp->_size];
(hp->_size)++;
if (hp->_size >= hp->_capacity)
{
hp->_a = (HeapDateType*)realloc(hp->_a, sizeof(HeapDateType)* 2* hp->_capacity);
hp->_capacity = 2 * hp->_capacity;
}
}
}
void HeapMake(Heap* hp)
{
assert(hp);
for (int i = (hp->_size - 2) / 2; i >= 0; i--)
{
HeapAdjustDown(&(*hp), i);
}
}
void HeapAdjustDown(Heap* hp, int root)
{
size_t parant = root;
size_t child = (root * 2) + 1;
while (child < hp->_size)
{
if (child + 1 < hp->_size && hp->_a[child] < hp->_a[child + 1])
{
child++;
}
if (hp->_a[parant] < hp->_a[child])//大堆 if (hp->_a[parant] > hp->_a[child])//小堆
{
Swap(&(hp->_a[parant]), &(hp->_a[child]));
parant = child;
child = (parant * 2) + 1;
}
else
{
break;
}
}
}
void HeapPush(Heap* hp, HeapDateType x)
{
assert(hp);
if (hp->_size >= hp->_capacity)
{
HeapDateType* newhp = (HeapDateType*)malloc(sizeof(HeapDateType*) * (hp->_capacity * 2));
assert(newhp);
for (size_t i = 0; i < hp->_size; i++)
{
newhp[i] = hp->_a[i];
}
free(hp->_a);
hp->_a = newhp;
hp->_capacity = hp->_capacity * 2;
}
hp->_a[hp->_size] = x;
hp->_size++;
HeapAdjustUp(&(*hp), hp->_size - 1);
}
void Swap(HeapDateType* a, HeapDateType* b)
{
size_t tmp = 0;
tmp = *a;
*a = *b;
*b = tmp;
}
void HeapAdjustUp(Heap* hp, int child)
{
size_t parant = (child - 1) / 2;
while (child > 0)
{
if (hp->_a[child] > hp->_a[parant])//大堆 if(hp->_a[child] < hp->_a[parant])//小堆
{
Swap(&(hp->_a[child]), &(hp->_a[parant]));
child = parant;
parant = (child - 1) / 2;
}
else
{
break;
}
}
}
void HeapPop(Heap* hp)
{
assert(hp);
Swap(&(hp->_a[0]), &(hp->_a[hp->_size - 1]));
--hp->_size;
HeapAdjustDown(&(*hp), 0);
}
size_t HeapSize(Heap* hp)
{
assert(hp);
return hp->_size;
}
size_t HeapEmpty(Heap* hp)
{
assert(hp);
return hp->_size;
}
HeapDateType HeapTop(Heap* hp)
{
assert(hp);
return hp->_a[0];
}
void HeapSort(Heap* hp)
{
assert(hp);
size_t i = hp->_size;
while (hp->_size > 0)
{
Swap(&(hp->_a[0]), &(hp->_a[hp->_size - 1]));
--(hp->_size);
HeapAdjustDown(hp, 0);
}
hp->_size = i;
}
void Print(Heap* hp)
{
assert(hp);
size_t i = 0;
for (; i < hp->_size; i++)
{
printf("%d ", hp->_a[i]);
}
}
数据结构—堆(数据类型int)
最新推荐文章于 2024-08-17 10:27:29 发布