C 언어 알고리즘과 데이터 구조 - 최소 무더기의 실현 (판자)

코드는 절강대학 MOOC의 과정을 감안한다.
         n
     n  ,     
#include
#include 
#define ElementType int
#define MinData 1000;
typedef struct HeapStruct* MinHeap;
struct HeapStruct{
    ElementType *Elements;
    int Size;
    int Capacity;
};
MinHeap Creat(int MaxSize)
{
    MinHeap H = malloc(sizeof(struct HeapStruct));
    H->Elements = malloc((MaxSize + 1) * sizeof(ElementType));
    H->Size = 0;
    H->Capacity = MaxSize;
    return H;
}
int IsFull(MinHeap H)
{
    if(H->Size < H->Capacity)   return 0;
    else return 1;
}
int IsEmpty(MinHeap H)
{
    if(H->Size == 0)    return 1;
    else return 0;
}
void Insert(MinHeap H, ElementType item)
{
    int i;
    if(IsFull(H)) {
        printf("full");
        return;
    }
    i = ++H->Size;
    for( ; i > 1 && H->Elements[i/2] > item; i /= 2)
        H->Elements[i] = H->Elements[i/2];
    H->Elements[i] = item;
}
ElementType Delete(MinHeap H)
{
    int Parent, Child;
    ElementType MinItem, temp;
    if(IsEmpty(H)) {
        printf("empty");
        return -1;
    }
    MinItem = H->Elements[1];
    temp = H->Elements[H->Size--];
    for(Parent = 1; Parent * 2 <= H->Size; Parent = Child) {
        Child = Parent * 2;
        if((Child != H->Size) && (H->Elements[Child] > H->Elements[Child + 1]))
            Child++;
        if(temp <= H->Elements[Child])  break;
        else H->Elements[Parent] = H->Elements[Child];
    }
    H->Elements[Parent] = temp;
    return MinItem;
}
int main()
{
    int N, i;
    scanf("%d", &N);
    MinHeap minh = Creat(N);
    for(i = 0; i < N; i++) {
        int temp;
        scanf("%d", &temp);
        Insert(minh, temp);
    }
    return 0;
}

좋은 웹페이지 즐겨찾기