Write the routines to do a ' percolate up ' and a ' percolate down ' in a binary min-heap.
Format of functions:
void PercolateUp( int p, PriorityQueue H );void PercolateDown( int p, PriorityQueue H );
Where int p
is the position of the element, and is defined as the PriorityQueue
following:
typedef struct HeapStruct *PriorityQueue;struct HeapStruct { ElementType *Elements; int Capacity; int Size;};
Sample Program of Judge:
#include <stdio.h> #include <stdlib.h>typedef int elementtype; #define MINDATA-1TYPEDEF struct heapstruct * Priorityqueue;struct heapstruct {ElementType *elements; int capacity; int Size;}; Priorityqueue Initialize (int maxelements); /* Details omitted */void percolateup (int p, priorityqueue h), void Percolatedown (int p, priorityqueue H), void Insert ( ElementType X, Priorityqueue H) {int p = ++h->size; H->ELEMENTS[P] = X; Percolateup (P, H);} ElementType deletemin (Priorityqueue H) {ElementType minelement; Minelement = h->elements[1]; H->ELEMENTS[1] = h->elements[h->size--]; Percolatedown (1, H); return minelement; }int Main () {int n, I, OP, X; Priorityqueue H; scanf ("%d", &n); H = Initialize (n); for (i=0; i<n; i++) {scanf ("%d", &op); Switch (OP) {case 1:scanf ("%d", &x); Insert (X, H); Break Case 0:printf ("%D ", Deletemin (H)); Break }} printf ("\ninside H:"); for (I=1; i<=h->size; i++) printf ("%d", h->elements[i]); return 0;} /* Your function would be put here */
Sample Input:
91 101 51 201 91 11 400
Sample Output:
2 1 4 Inside H: 5 10 9
Answer:
This problem is really good water ah ... and the input and output sample is necessary to give ... Just write the minimum heap insert and delete operation is good ... It's all a regular operation.
////main.c//percolate up and down////Created by Yunanrong on 2016/10/31.//Copyright 2016 Yunanrong. All rights reserved.//voidPercolateup (intp, Priorityqueue H) {ElementType tmp= h->Elements[p]; while(P/2>=1&&h->elements[p/2] >tmp) {H->ELEMENTS[P] = h->elements[p/2]; P= P/2; } H->ELEMENTS[P] =tmp;}voidPercolatedown (intp, Priorityqueue H) {ElementType tmp= h->Elements[p]; while(1){ if(P *2+1<= h->Size) { if(H->ELEMENTS[P *2+1] < H->elements[p *2]&&h->elements[p *2+1] <tmp) {H->ELEMENTS[P] = h->elements[p *2+1]; P= P *2+1; } Else if(H->ELEMENTS[P *2+1] > H->elements[p *2]&&h->elements[p *2] <tmp) {H->ELEMENTS[P] = h->elements[p *2]; P= P *2; } Else{ Break; } } Else if(P *2<= h->Size) { if(H->ELEMENTS[P *2] <tmp) {H->ELEMENTS[P] = h->elements[p *2]; P= P *2; } Else{ Break; } } Else{ Break; }} H->ELEMENTS[P] =tmp;}
PTA percolate up and down