堆 Heap

記錄下小頂堆

#include <stdio.h>
#include <stdlib.h>

#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等價(jià)于i=i/2;這里的首先是0開(kāi)始所以i= h->size - 1;
    {
        //i/2父節(jié)點(diǎn)位置
        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類(lèi)型占4個(gè)字節(jié) sizeof()算出的是該數(shù)組總的字節(jié)數(shù)
    int i = 0;
    heap h = InitHeap();
    for (; i < length; i++)
    {
        h->size++;
        h->data[i] = a[i];
    }
    int b = 9;
    printf("插入的數(shù)字為:%d\n", b);
    InsertHeap(h, b);
    // printf("堆的輸出結(jié)果為:%d", a[1999]);
    printf("堆的輸出結(jié)果為:");
    PrintHeap(h);
    return 0;
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容