建立最大堆

来源:互联网 发布:is网络同步工具 编辑:程序博客网 时间:2024/06/06 03:53

建立最大堆与删除最大堆根节点算法类似,都需要依次下滤父结点。

typedef struct HNode *Heap;struct HNode{int *Data;//存储元素的数组;int size;int capacity;};typedef Heap MaxHeap;typedef Heap MinHeap;#define MAXDATA 1000MaxHeap CreatHeap(int MaxSize){MaxHeap H=(MaxHeap)malloc(sizeof(struct HNode);H->Data=(int *)malloc((MaxSize+1)*sizeof(int));H->size=0;H->capacity=MaxSize;H->Data[0]=MAXDATA;//哨兵元素;return H;}bool isFull(MaxHeap H){return (H->size==H->capacity);}bool Insert(MaxHeap H,int X){//插入X;int father,son;if(isFull(H){printf("full");return false;}i=++H->size;for(;H->Data[i/2]<X;i/=2)H->Data[i]=H->Data[i/2];H->Data[i]=X;return true;}int DeleteMax(MaxHeap H){//删除最大值,int father,son;int X=H->Data[H->size--];Max=H->Data[1];for(father=1;(father*2)<H->size;father=son){son=father*2;for((son!=H->size)&&H->Data[son]<H->Data[son+1])son++;if(H->Data[son]<=X) break;elseH->Data[father]=H->Data[son];}H->Data[father]=X;return Max;}//建立最大堆void PercDown(MaxHeap H,int p){int father,son;int X=H->Data[p];for(father=H->Data[p];(father*2)<H->size;father=son){son=father*2;if((son!=H->size)&&H->Data[son]<H->Data[son+1])son++;if(X>=H->Data[son])break;elseH->Data[father]=H->Data[son];}H->Data[father]=X;}void BuildHeap(MaxHeap H){int i;//从最后一个元素父结点开始,依次建堆for(i=H->size/2;i>0;i--)//注意这里,是大于0,不是大于1,需要依次将元素下滤PercDown(H,i);}


原创粉丝点击