最大堆

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
struct node {
    int *num;
    int Size; //堆的当前元素数量
    int Capacity; //堆的最大容量
};
node *CreatHeap(int maxSize) {
    node *maxHeap = (node *) malloc(sizeof(node));
    if(!maxHeap) return NULL;
    maxHeap->num = (int *) malloc(sizeof(int) * maxSize);
    maxHeap->Size = 0; maxHeap->Capacity = maxSize;
    maxHeap->num[0] = INF;
    return maxHeap;
}
bool isFull(node *H) {
    return H->Size == H->Capacity;
}
void Insert(node *maxHeap, int x) {
    if(isFull(maxHeap)) {
        printf("the maxHeap is FULL\n");
        return ;
    }
    int i = ++(maxHeap->Size);
    while(maxHeap->num[i/2] < x) {
        maxHeap->num[i] = maxHeap->num[i/2];
        i /= 2;
    }
    maxHeap->num[i] = x;
}
bool isEmpty(node *H) {
    return H->Size == 0;
}
int DeleteMax(node *maxHeap) {
    if(isEmpty(maxHeap)) {
        printf("The maxHeap is Empty\n");
        return -1;
    }
    int Maxn = maxHeap->num[1];
    int tmp = maxHeap->num[(maxHeap->Size)--];
    int parent, child;
    for(parent = 1; parent*2 <= maxHeap->Size; parent = child) {
        child = parent * 2;
        if(child != maxHeap->Size &&
           maxHeap->num[child] < maxHeap->num[child+1]) {
            child++;
        }
        if(tmp >= maxHeap->num[child]) break;
        else {
            maxHeap->num[parent] = maxHeap->num[child];
        }
    }
    maxHeap->num[parent] = tmp;
    return Maxn;
}
int main()
{
    node *maxHeap = CreatHeap(10);
    for(int i = 0; i < 11; i++) {
        Insert(maxHeap, i);
    }
    for(int i = 0; i <= maxHeap->Size; i++) {
        printf("%d ", maxHeap->num[i]);
    }
    printf("\n");
    for(int i = 0; i < 11; i++) {
        printf("%d ", DeleteMax(maxHeap));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值