6-13 Percolate Up and Down(20 point(s))
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 PriorityQueue
is defined as the 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 -1
typedef 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 will be put here */
Sample Input:
9
1 10
1 5
1 2
0
1 9
1 1
1 4
0
0
Sample Output:
2 1 4 Inside H: 5 10 9 code:
void PercolateUp( int p, PriorityQueue H ){ int i = p; int flag = 0; if(i==1)return; while(i!=1 && flag==0){ if(H->Elements[i]<H->Elements[i/2]){//比父节点小,交换 int temp = H->Elements[i]; H->Elements[i] = H->Elements[i/2]; H->Elements[i/2] = temp; } else flag = 1;//否则不需要调整flag变1 i = i/2;//每次向上找父节点 } return; } void PercolateDown( int p, PriorityQueue H ){ int t;//记录较小元素下标,如果发现t和原来的没变则不用再继续调整了,如果t变成了原来的儿子下标,说明继续向下调整 int flag = 0;//标记是否需要继续调整 int i = p; while(i*2<=H->Size&&flag==0){//注意!!i*2<=n才能进行下面的比较,如果单纯i<=n如果i=n,乘二肯定没有了 if(H->Elements[i]>H->Elements[i*2]){//比较当前点和左儿子的大小,如果现在元素大于左二子,则调整 t = i*2; } else//如果和左儿子比当前元素小,让t等于它本身 t = i; if(i*2+1<=H->Size){//如果含有右儿子,则需要比较右儿子 if(H->Elements[t]>H->Elements[i*2+1]){//如果之前得到的最小的还比右儿子大 t = i*2+1;//修改t的值 } } if(t==i){ flag = 1;//如果t的值还是i本身则说明不需要继续调整了 } else{ //交换 int temp = H->Elements[i]; H->Elements[i] = H->Elements[t]; H->Elements[t] = temp; i = t;//继续调整i值变成当前t } } }