Heap
Heap
h> typedef int ElementType; struct HeapStruct; typedef struct HeapStruct *PriorityQueue;
PriorityQueue Initialize(int MaxElements); void Insert(ElementType X, PriorityQueue H); ElementType DeleteMin(PriorityQueue H); ElementType FindMin(PriorityQueue H); int IsEmpty(PriorityQueue H); int IsFull(PriorityQueue H); void display(PriorityQueue H); #define MinPQSize (10) #define MinData (-32767) struct HeapStruct { int Capacity; int Size; ElementType *Elements; }; PriorityQueue Initialize(int MaxElements) { PriorityQueue H; /* 1*/ if (MaxElements < MinPQSize) /* 2*/ printf("Priority queue size is too small"); /* 3*/ H =(struct HeapStruct *) malloc(sizeof ( struct HeapStruct)); /* 4*/ if (H == NULL) /* 5*/ ("Out of space!!!"); /* Allocate the array plus one extra for sentinel */ /* 6*/ H->Elements =(int *) malloc((MaxElements + 1) * sizeof ( ElementType)); /* 7*/ if (H->Elements == NULL) /* 8*/ printf("Out of space!!!"); /* 9*/ H->Capacity = MaxElements; /*10*/ H->Size = 0; /*11*/ H->Elements[ 0 ] = MinData; /*12*/ return H; }
/* END */
/* H->Element[ 0 ] is a sentinel */ void Insert(ElementType X, PriorityQueue H) { int i; if (IsFull(H)) { printf("Priority queue is full"); return; } for (i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2) H->Elements[ i ] = H->Elements[ i / 2 ]; H->Elements[ i ] = X; } /* END */ ElementType DeleteMin(PriorityQueue H) { int i, Child; ElementType MinElement, LastElement; /* 1*/ if (IsEmpty(H)) { /* 2*/ printf("Priority queue is empty"); /* 3*/ return H->Elements[ 0 ]; } /* 4*/ MinElement = H->Elements[ 1 ]; /* 5*/ LastElement = H->Elements[ H->Size-- ]; /* 6*/ for (i = 1; i * 2 <= H->Size; i = Child) { /* Find smaller child */ /* 7*/ Child = i * 2; /* 8*/ if (Child != H->Size && H->Elements[ Child + 1 ] /* 9*/ < H->Elements[ Child ]) /*10*/ Child++; /* Percolate one level */ /*11*/ if (LastElement > H->Elements[ Child ]) /*12*/ H->Elements[ i ] = H->Elements[ Child ]; else /*13*/ break; }
/*14*/ H->Elements[ i ] = LastElement; /*15*/ return MinElement; } ElementType FindMin(PriorityQueue H) { if (!IsEmpty(H)) return H->Elements[ 1 ]; printf("Priority Queue is Empty"); return H->Elements[ 0 ]; } int IsEmpty(PriorityQueue H) { return H->Size == 0; } int IsFull(PriorityQueue H) { return H->Size == H->Capacity; } void display(PriorityQueue H) { int i=1;printf("the elements in the priority queue are\t"); while(i<=H->Size) { printf("%d\t",H->Elements[i]); i++; } } #define MaxSize (1000) main() { PriorityQueue H; int b,a,j,n; H = Initialize(MaxSize); while(1) { printf("\nenter your choice.......1.insert 2.delete min 3.findmin 4.display 5.exit\n"); scanf("%d",&b); switch(b) { case 1:
printf("enter the no."); scanf("%d",&j); Insert(j, H); break; case 4: display(H); break; case 2: n=DeleteMin(H); printf("the deleted element is %d\n",n); break; case 3: a=FindMin(H); printf("the minimum element="); printf("%d\n",a); break; case 5: exit(0);break; }}}