数据结构之堆

实现堆的创建,出堆等操作

#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);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值