数据结构与算法分析-二叉堆的实现

 #ifndef _BINARY_HEAP_H #define _BINARY_HEAP_H struct HeapStruct; typedef struct HeapStruct *PriorityQueue; PriorityQueue Initialize( int MaxElement ); void Destory( PriorityQueue H ); void PrintQueue( PriorityQueue H ); void MakeEmpty( PriorityQueue H ); void Insert( int X, PriorityQueue H ); int DeleteMin( PriorityQueue H ); int FindMin( PriorityQueue H ); int IsEmpty( PriorityQueue H ); int IsFull( PriorityQueue H ); #endif _BINARY_HEAP_H

 

#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> #include "heapbin.h" int MinData = -1; struct HeapStruct { int Capacity; int Size; int *Element; }; int MinPQSize = 17; int IsPQFull( PriorityQueue H ) { return H->Size == H->Capacity; } int IsPQEmpty( PriorityQueue H ) { return H->Size == 0; } PriorityQueue Initialize( int MaxElement ) { PriorityQueue H; if ( MaxElement < MinPQSize ) { printf("Priority queue size is too small/n"); return NULL; } H = malloc( sizeof( struct HeapStruct ) ); assert( H != NULL ); H->Element = malloc( ( MaxElement + 1 ) * sizeof( int ) ); assert( H->Element != NULL ); H->Capacity = MaxElement; H->Size = 0; H->Element[ 0 ] = MinData; return H; } void Insert( int X, PriorityQueue H ) { int i; if ( IsPQFull( H ) ) { printf("Priority queue is full/n"); return; } for ( i = ++H->Size; H->Element[ i / 2 ] > X; i /= 2 ) { H->Element[ i ] = H->Element[ i / 2 ]; } H->Element[ i ] = X; } int FindMin( PriorityQueue H ) { return H->Element[ 1 ]; } int DeleteMin( PriorityQueue H ) { int i, Child; int MinElement, LastElement; if ( IsPQEmpty( H ) ) { printf("Priority is empty/n"); return H->Element[ 0 ]; } MinElement = H->Element[ 1 ]; LastElement = H->Element[ H->Size-- ]; for ( i = 1; i * 2 <= H->Size; i = Child ) { Child = i * 2; if ( Child != H->Size && H->Element[ Child+1 ] < H->Element[ Child ] ) Child++; if ( LastElement > H->Element[ Child ] ) H->Element[ i ] = H->Element[ Child ]; else break; } printf("********%d/n", i); H->Element[ i ] = LastElement; return MinElement; } void PrintQueue( PriorityQueue H ) { int i; printf("------------/n"); for ( i = 1; i <= H->Size; i++ ) { printf("---%d--%d---/n", i, H->Element[ i ] ); } } int main( int argc, char **argv ) { PriorityQueue queue; queue = Initialize( 21 ); Insert( 13, queue ); Insert( 21, queue ); Insert( 16, queue ); Insert( 24, queue ); Insert( 31, queue ); Insert( 19, queue ); Insert( 68, queue ); Insert( 65, queue ); Insert( 26, queue ); Insert( 32, queue ); PrintQueue( queue ); Insert( 14, queue ); PrintQueue( queue ); DeleteMin( queue ); PrintQueue( queue ); return 0; }

你可能感兴趣的:(数据结构,算法,struct,null,insert)