Max Heap C Implementation
Max Heap C Implementation
int maxheap_max( maxheap ) ; int maxheap_insert( maxheap , int , char* ) ; int maxheap_deletemax( maxheap ) ;
#endif
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "maxheap.h"
/* create a new empty heap */ maxheap maxheap_create() { maxheap h = (maxheap) malloc( sizeof( struct maxheap_rep ) ) ; if ( !h ) {
h->array = (int * ) malloc( sizeof(int) * (h->maxsize+1) ) ; h->array_c = (char * ) malloc( sizeof(char) * (h->maxsize+1) ) ;
return h ; }
assert( H && H->array && H->array_c) ; free( H->array ) ; free( H->array_c ) ; free( H ) ; }
assert ( H && i>=1 && i<=H->cursize && j>= 1 && j <= H->cursize ) ;
/* fix bottom-up the k-th element assuming that its priority has been increased */ void maxheap_fixup ( maxheap H , int k )
/* fix top-down the k-th element assuming that its priority has been decreased */ void maxheap_fixdown ( maxheap H , int k ) { int tmp ; int j ; assert ( H ) ;
while ( 2*k <= H->cursize ) { j = 2*k ; if ( j < H->cursize && H->array[j]< H->array[j+1]) j++; if ( H->array[k] >= H->array[j]) break ;
maxheap_swap ( H , k , j ) ; k = j; } }
if ( H->cursize == H->maxsize ){ printf("Max heap is full! \nYou can not insert more items!\n\n"); return 0; }
H->cursize++;
// add at the bottom, as a leaf H->array [ H->cursize ] = item ; H->array_c [ H->cursize ] = item1[0] ;
return 1; }
/* return the max element of a heap */ int maxheap_max( maxheap H ) { if ( maxheap_empty(H) ) { fprintf(stderr , "Max heap is empty!\n\n" ) ; return 0; }
return 1 ; }
return 1; }
while (1){
//input[strlen(input)-1] = '\0';
char delims[] = " "; char *result = NULL; result = strtok( input, delims );
if ( atoi(priority)>=1 && atoi(priority)<=99 ){ if( maxheap_insert( H , atoi(priority) , item )) printf("Item %s with priority %s inserted\n\n", item , priority ); continue; } else{ printf("Priority out of bounds:\t1 <= p <= 99\n\n"); continue; } }
if(!strcmp("max", result)){
maxheap_max(H); continue; }
if(!strcmp("extract", result)){ result = strtok( NULL, delims ); if(!strcmp("max", result)){ printf("Heap's max element is being removed... \t"); if ( maxheap_deletemax( H ) ) continue; } else { printf("Please give a valid command\n\n"); continue; } } printf("Done\n\n");
break; }
if(!strcmp("help", result)){ printf("\nList of commands: \ninsert C P \nmax \nextract max \nsize \nexit \n\n"); continue; }
sleep(1000); }