实现堆的创建,出堆等操作
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef struct Heap
{
int array[100];
int size;
}Heap;
//初始化堆
void HeapInit(Heap *pH, int array, int size)
{
assert(pH);
memcpy(pH->array,array,sizeof(int)*size);
pH->size = size;
}
void Swap(int *p, int *q)
{
*p ^= *q;
*q ^= *p;
*p ^= *q;
}
//向下调整(递归)
void AdiustDownRecursion(Heap *pH, int parent)
{
int leftChild = 2 * parent + 1;
int rightChild = 2 * parent + 2;
int maxChild;
if (leftChild >= pH->size)
{
return;//叶子结点
}
maxChild = leftChild;
if (rightChild < pH->size&&pH->array[leftChild] < pH->array[rightChild])
{
maxChild = rightChild;
}
if (pH->array[parent] < pH->array[maxChild])
{
Swap(&(pH->array[parent]), &(pH->array[maxChild]));
}
AdiustDownRecursion(pH ,maxChild);
}
//向下调整非递归实现
void AdiustDown(Heap *pH, int parent)
{
while (1)
{
int leftChild = 2 * parent + 1;
int rightChild = 2 * parent + 2;
int maxChild;
if (leftChild >= pH->size)
{
return;//叶子结点
}
maxChild = leftChild;
if (rightChild < pH->size&&pH->array[leftChild] < pH->array[rightChild])
{
maxChild = rightChild;
}
if (pH->array[parent] < pH->array[maxChild])
{
Swap(&(pH->array[parent]), &(pH->array[maxChild]));
}
parent = maxChild;
}
}
//建大堆
void HeapMake(Heap *pH)
{
int i = 0;
for (i = (pH->size -1 -1) / 2; i >= 0; i--)//从最后一个非叶子结点开始
{
AdiustDownRecursion(pH->array, i);
}
}
int HeapTop(Heap *pH)
{
return pH->array[0];
}
int HeapSize(Heap *pH)
{
return pH->size;
}
int HeapIsEmpty(Heap *pH)
{
return pH->size == 0 ? 1 : 0;//为空返回1,不为空返回0
}
//出堆
void HeapPop(Heap *pH)
{
assert(pH);
assert(pH->size > 0);
pH->array[0] = pH->array[pH->size - 1];//将最后一个叶子结点放到第一个
pH->size--;
AdiustDownRecursion(pH, 0);
}
//向上调整
void AdjustUp(Heap *pH, int child)
{
while (1)
{
int parent = (child - 1) / 2;
if (child == 0)
{
return;
}
if (pH->array[child] > pH->array[parent])
{
Swap(pH ->array+ child, pH->array + parent);
}
child = parent;
}
}
//堆插入
void Insert(Heap *pH, int data)
{
assert(pH);
pH->array[pH->size++] = data;
AdjustUp(pH, pH->size - 1);
}