1.堆是一个完全二叉树,在大(小)顶堆中,满足每一个父节点都比它的所有孩子结点的值要大(小)。

2.堆一般用数组来存储(完全二叉树)。

堆的实现:

 /*
        1.初始化 
        2.判满 
        3.插入                    //时间复杂度O(logN) 
        4.判空
        5.删除最大元素 
        6.创建                     //O(n)
*/
#include<cstdio>
#include<cstdlib>
#include<limits.h>
typedef int ElementType;
typedef struct heap{
    ElementType* data;
    int size;
    int capacity;
}heap;
//初始化一个大小为MaxSize的最大堆
heap Init(int MaxSize){
    heap h;
    h.data=(ElementType*)malloc((MaxSize+1)*sizeof(ElementType));//0号位置不放元素,放一个哨兵大于堆中所以元素的最大值 
    h.size=0;
    h.capacity=MaxSize;
    h.data[0]=INT_MAX; 
    return h;
}
bool isFull(heap h){
    if(h.size==h.capacity)
        return true;
    return false;
}
void Insert(heap& h,ElementType X){    
    if(isFull(h)){    
        printf("堆满");
        return;
    }
    int i=++h.size;
    for(;X>h.data[i/2];i/=2){t
        h.data[i]=h.data[i/2];
    }
    h.data[i]=X;
    
}
bool isEmpty(heap h){
    if(h.size==0)
        return true;
    else
        return false;
}
ElementType DeleteMax(heap &h){
    if(isEmpty(h)){
        printf("堆空");
        return -1;
    }
    int parent,child;
    ElementType MaxItem,temp;
    MaxItem=h.data[1];
    temp=h.data[h.size--];
    for(parent=1;parent*2<=h.size;parent=child){
        child=parent*2;
        if(h.data[child+1]>h.data[child]&&child+1<=h.size){
            child++;
        }
        if(temp<h.data[child])
            h.data[parent]=h.data[child];
        else
            break;
    }
    h.data[parent]=temp;
    return MaxItem;
}
void PercDown(heap &h,int parent){
    int child;
    int temp=h.data[parent];
    for(;parent*2<=h.size;parent=child){
        child=parent*2;
        if((child+1)<=h.size&&h.data[child+1]>h.data[child])
            child++;
        if(h.data[child]<=temp)
            break; 
        else
            h.data[parent]=h.data[child];
    }
    h.data[parent]=temp;
}
void buildHeap(heap &h){
    int n=h.size;
    for(int i=n/2;i>0;i--){
        PercDown(h,i);
    }
} 
int main(){
    return 0;
} 

 

posted @ 2020-10-21 21:09  9761滴  阅读(118)  评论(0编辑  收藏  举报