最大/小堆的声明
typedef struct HNode *Heap;
struct HNode{
ElementType *Data;
int Size;
int Capacity;
};
typedef Heap MaxHeap;
typedef Heap MinHeap;
最大堆的创建
#define MaxData 1000
MaxHeap CreateHeap(int MaxSize){
MaxHeap H=(MaxHeap)malloc(sizeof(struct HNode));
H->Data=(ElementType *)malloc((MaxSize+1)*sizeof(ElementType));
H->Size=0;
H->Capacity=MaxSize;
H->Data[0]=MaxData;
return H;
}
最大堆的插入操作
bool IsFull(MaxHeap H){
return (H->Capacity==H->Size);
}
bool Insert(MaxHeap H,ElementType X){
int i;
if(IsFull(H)){
printf("堆已满,插不进啦");
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 ture;
}
从最大堆总取出键值最大的元素
bool IsEmpty(MaxHeap H){
return (H->Size==0)
}
ElementType DeleteMax(MaxHeap H){
int Parent,Child;
ElementTyepe MaxItem,X;
if(IsEmpty(H)){
printf("堆是空的");
return false;
}
MaxItem=H->Data[1];
X=H->Data[Size--];
for(Parent=1; Parent*2<=H->Size ;Parent=Child){
Child=2*Parent;
if((Child!=H->Size)&&H->Data[Child] < H->Data[Child+1])
Child++;
if(H->Data[Child]<=X)
break;
else
H->Data[Parent]=H->Data[Child];
}
H->Data[Parent]=X;
return MaxItem
}
建立最大堆
void PercDown(MaxHeap H,int i){
int Parent,Child;
ElementType X;
X=H->Data[p];
for(Parent=p ; 2*Parent<=H->Size; Parent=Child){
Child=Parent*2;
if((Child!=H->Size)&&H->Data[Child] < H->Data[Child+1])
Child++;
if(X >= H->Data[Child])
break;
else
H->Data[Parent]=H->Data[Child];
}
H->Data[Parent]=X;
}
void BuildHeap(MaxHeap){
int i;
for(i=H->Size/2;i>0;i--)
PercDown(H,i);
return 0;
}