#include <stdio.h> #include <stdlib.h> #include <limits.h> //if want to change MinHeap into MaxHeap,need to change four places //MaxHeap INT_MAX #define MINDATA INT_MIN typedef int ElementType; struct MinHeap { int TotalCapacity; int CurrentSize; ElementType *HeapData; }; struct MinHeap *MinHeapInit(int TotalCapa) { struct MinHeap *Heap; Heap = malloc(sizeof(struct MinHeap)); Heap -> HeapData = malloc((TotalCapa+1)*sizeof(ElementType)); Heap -> HeapData[0] = MINDATA; Heap -> TotalCapacity = TotalCapa; Heap -> CurrentSize = 0; return Heap; } int MinHeapIsEmpty(struct MinHeap *Heap) { return (Heap -> CurrentSize == 0); } int MinHeapIsFull(struct MinHeap *Heap) { return (Heap -> CurrentSize == Heap -> TotalCapacity); } int MakeMinHeapEmpty(struct MinHeap *Heap) { Heap -> TotalCapacity = Heap -> CurrentSize = 0; free(Heap -> HeapData); Heap -> HeapData = NULL; return 0; } int MinHeapDestroy(struct MinHeap *Heap) { MakeMinHeapEmpty(Heap); free(Heap); Heap = NULL; return 0; } //if Heap is full,return 1 int MinHeapInsert(struct MinHeap *Heap,ElementType ToBeInsert) { int i; if(MinHeapIsFull(Heap)) { return 1; } //MaxHeap < for(i = ++Heap->CurrentSize;Heap->HeapData[i/2] > ToBeInsert;i /= 2) { Heap -> HeapData[i] = Heap -> HeapData[i/2]; } Heap -> HeapData[i] = ToBeInsert; return 0; } //if Heap is Empty,return MINDATA ElementType MinHeapDeleteMin(struct MinHeap *Heap) { int i; int Child; int MinimumElement,LastElement; if(MinHeapIsEmpty(Heap)) { return Heap -> HeapData[0]; } MinimumElement = Heap -> HeapData[1]; LastElement = Heap -> HeapData[Heap -> CurrentSize --]; for(i = 1;i*2 <= Heap->CurrentSize;i = Child) { //Find smaller child Child = i*2; //MaxHeap > if(Child != Heap->CurrentSize && Heap->HeapData[Child+1] < Heap->HeapData[Child]) { Child ++; } //MaxHeap < if(LastElement > Heap -> HeapData[Child]) { Heap -> HeapData[i] = Heap -> HeapData[Child]; } else { break; } } Heap -> HeapData[i] = LastElement; return MinimumElement; } //if Heap is Empty,return MINDATA ElementType MinHeapFindMin(struct MinHeap *Heap) { if(MinHeapIsEmpty(Heap)) { return Heap -> HeapData[0]; } return Heap -> HeapData[1]; } int main() { int i; int TestArray[10] = {2,5,3,5,6,1,4,8,9,1}; struct MinHeap *Heap = MinHeapInit(10); for(i = 0;i < 10;i ++) { MinHeapInsert(Heap,TestArray[i]); } MinHeapDeleteMin(Heap); MinHeapDeleteMin(Heap); for(i = 1;i < Heap->CurrentSize+1;i ++) { printf("%d ",Heap->HeapData[i]); } printf(" "); MinHeapDestroy(Heap); return 0; }