堆建立(自用)

heap.h

#pragma once
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
typedef int HeapDataType;
typedef struct Heap
{
    HeapDataType* _a;
    int _size;
    int _capacity;


}Heap;
void Swap(HeapDataType* p1, HeapDataType* p2);
void AdjustDown(HeapDataType* a, int n,int root);

void  HeapInit(Heap* php, HeapDataType* a, int n);
void HeapDestory(Heap* php);
void HeapPush(Heap* php,HeapDataType x);
void HeapPop(Heap* php);
HeapDataType HeapTop(Heap* php);
 

heap.c

#include"Heap.h"
void  HeapInit(Heap* php, HeapDataType* a, int n)
{
    php->_a = (HeapDataType*)malloc(sizeof(HeapDataType) * n);
    memcpy(php->_a, a, sizeof(HeapDataType)*n);
    php->_size = n;
    php->_capacity = n;
    //构建堆
    for (int i = (n - 1 - 1) / 2; i >= 0; --i)
    {
        AdjustDown(php->_a, php->_size, i);
    }

}
void Swap(HeapDataType* p1, HeapDataType* p2)
{
    HeapDataType tmp = *p1;
    *p1 = *p2;
    *p2 = tmp;
}
void AdjustUp(HeapDataType* a, int n, int child)
{
    int parent = (child - 1) / 2;
    while (child)
    {
        if (a[child] < a[parent])
        {
            Swap(&a[child],& a[parent]);

            child = parent;
            parent = (child - 1) / 2;
        }
        else
        {
            break;
        }
    }
}
void AdjustDown(HeapDataType* a, int n,int root)
{
    int parent = root;
    int child = parent * 2 + 1;
    while (child<n)
    {
        if (child+1<n&&a[child + 1] < a[child])
        {
            ++child;
        }
        if (a[child] < a[parent])
        {
            Swap(&a[child], &a[parent]);
        }
        else
        {
            break;
        }
    }
}
void HeapDestory(Heap* php)
{
    assert(php);
    free(php->_a);
    php->_a = NULL;
    php->_capacity = php->_size = 0;
}
void HeapPush(Heap* php, HeapDataType x)
{
    assert(php);
    if (php->_size == php->_capacity)
    {
        php->_capacity *= 2;
        HeapDataType* tmp =(HeapDataType*) realloc(php->_a,sizeof(HeapDataType) * php->_capacity);

        php->_a = tmp;
    }
    php->_a[php->_size++] = x;
    AdjustUp(php->_a, php->_size, php->_size - 1);

}
void HeapPop(Heap* php)
{
    assert(php);
    assert(php->_size > 0);

    Swap(&php->_a[0], &php->_a[php->_size - 1]);
    php->_size--;

    AdjustDown(php->_a, php->_size, 0);
}
HeapDataType HeapTop(Heap* php)
{
    assert(php);
    assert(php->_size);
    return php->_a[0];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值