堆 Heap

记录下小顶堆

#include 
#include 

#define CAPCITY 8 //capcity容量

typedef struct MinHeap
{
    int size;
    int data[CAPCITY];
} MinHeap, *heap;

heap InitHeap()
{
    heap h;
    h = (heap)malloc(sizeof(MinHeap));
    h->size = 0;
    return h;
}

void InsertHeap(heap h, int data)
{
    if (h->size == CAPCITY)
    {
        printf("堆已满");
        return;
    }

    int i;
    h->size++;
    for (i = h->size - 1; i >= 1; i = i / 2) //i/=2等价于i=i/2;这里的首先是0开始所以i= h->size - 1;
    {
        //i/2父节点位置
        if (data < h->data[i / 2])
        {
            h->data[i] = h->data[i / 2];
        }
    }
    h->data[i] = data;
    return;
}
void PrintHeap(heap h)
{
    int i = 0;
    for (; i < h->size; i++)
    {
        printf("%d,", h->data[i]);
    }
    return;
}
int IsEmpty(heap h)
{
    return h->size == 0 ? 1 : 0;
}
int main()
{
    int a[6] = {10, 20, 15, 25, 50, 30};
    int length = sizeof(a) / sizeof(a[0]); //int类型占4个字节 sizeof()算出的是该数组总的字节数
    int i = 0;
    heap h = InitHeap();
    for (; i < length; i++)
    {
        h->size++;
        h->data[i] = a[i];
    }
    int b = 9;
    printf("插入的数字为:%d\n", b);
    InsertHeap(h, b);
    // printf("堆的输出结果为:%d", a[1999]);
    printf("堆的输出结果为:");
    PrintHeap(h);
    return 0;
}

你可能感兴趣的:(堆 Heap)