1.定义结构
typedef int HTDataType;
typedef struct Heap
{
HTDataType* _a;
int _size;
int _capacity;
}Heap;
2.接口声明
void HeapInit(Heap* hp, HTDataType* a, int n);
void HeapDestory(Heap* hp);
void HeapPush(Heap* hp, HTDataType x);
void HeapPop(Heap* hp);
HTDataType HeapTop(Heap* hp);
int HeapSize(Heap* hp);
int HeapEmpty(Heap* hp);
void AdjustDown(HTDataType* a, int n, int parent);
void AdjustUp(HTDataType* a, int n, int child);
3.函数实现
#include "Heap.h"
static void Swap(HTDataType* a, HTDataType* b)
{
HTDataType tmp = *a;
*a = *b;
*b = tmp;
}
void AdjustDown(HTDataType* a, int n, int parent)
{
assert (a);
int child = 2 * parent + 1 ;
while (child < n)
{
if ((a[child] < a[child + 1 ])&&(child+1 != n))
{
child++;
}
if (a[parent] < a[child])
{
Swap(&a[parent], &a[child]);
parent = child;
child = 2 * parent + 1 ;
}
else
{
break ;
}
}
}
void HeapInit(Heap* hp, HTDataType* a, int n)
{
assert (hp);
hp->_capacity = 6 ;
hp->_a = (HTDataType*)malloc(sizeof(HTDataType)*(hp->_capacity));
hp->_size = 0 ;
int i = 0 ;
for (i = 0 ; i < n; i++)
{
hp->_a[i] = a[i];
hp->_size++;
}
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->_capacity = 0 ;
hp->_size = 0 ;
}
void AdjustUp(HTDataType* a, int n, int child)
{
assert (a);
int parent = (child - 1 ) / 2 ;
while (child > 0 )
{
if (a[parent] < a[child])
{
Swap(&a[parent], &a[child]);
child = parent;
parent = (child - 1 ) / 2 ;
}
else
{
break ;
}
}
}
void HeapPush(Heap* hp, HTDataType x)
{
assert (hp);
if (hp->_size == hp->_capacity)
{
hp->_capacity *= 2 ;
HTDataType* tmp = realloc(hp->_a, sizeof(HTDataType)*(hp->_capacity));
if (tmp != NULL)
{
hp->_a = tmp;
}
}
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 --;
AdjustDown(hp->_a, hp->_size, 0 );
}
HTDataType HeapTop(Heap* hp)
{
assert (hp);
return hp->_a[0 ];
}
int HeapSize(Heap* hp)
{
assert (hp);
return hp->_size;
}
int HeapEmpty(Heap* hp)
{
assert (hp);
return hp->_size == 0 ? 0 : 1 ;
}
void HeapSort(HTDataType* a, int n)
{
assert (a);
int index = n;
for (int i = (n - 2 ) / 2 ; i >= 0 ; i--)
{
AdjustDown(a, n, i);
}
while (index != 1 )
{
Swap(&a[0 ], &a[index - 1 ]);
index--;
AdjustDown(a, index, 0 );
}
for (int i = 0 ; i < n; i++)
{
printf("%d " , a[i]);
}
printf("\n" );
}
void PrintHeap(Heap* hp)
{
assert (hp);
for (int i = 0 ; i < hp->_size; i++)
{
printf("%d " , hp->_a[i]);
}
printf("\n" );
}
4.测试函数
void TestHeap()
{
Heap h;
HTDataType arr[] = { 17 , 18 , 68 , 28 , 54 , 87 };
int size = sizeof(arr) / sizeof(arr[0 ]);
HeapSort(arr, size);
HeapInit(&h, arr, size);
PrintHeap(&h);
HeapPush(&h, 100 );
PrintHeap(&h);
HeapPop(&h);
PrintHeap(&h);
printf ("堆的大小为:%d \n" , HeapSize(&h));
printf ("?空(空:0,非空:1):%d \n" , HeapEmpty(&h));
printf ("堆顶元素为:%d \n" , HeapTop(&h));
HeapDestory(&h);
}
int main()
{
TestHeap();
system ("pause" );
return 0 ;
}