void main(void) { int matrix[MAXSIZE][MAXSIZE] = { { 1, 3, 5, 7, 9, 10, 15, 20, 50, 80}, { 5, 6, 9, 11, 14, 19, 23, 45, 67, 78}, { 2, 10, 20, 23, 39, 47, 60, 75, 82, 90}, { 9, 18, 27, 42, 55, 76, 83, 87, 88, 91}, { 4, 9, 19, 29, 39, 49, 59, 69, 79, 99}}; int m = 5; int n = 10; int out[MAXSIZE*MAXSIZE]; int i, j; printf("\nHeap Merge Program"); printf("\n=================="); for (i = 0; i < m; i++) { printf("\n\nFile #%d :", i); for (j = 0; j < n; j++) { if (j % 10 == 0) printf("\n"); printf("%4d", matrix[i][j]); } } heap_merge(matrix, m, n, out); printf("\n\nThe Merged Result :"); for (i = 0; i < m*n; i++) { if (i % 10 == 0) printf("\n"); printf("%4d", out[i]); } }
/* ** Extend the heap by words_nbr * WORD_SIZE bytes. ** If words_nbr is not a multiple of 2, one word is added. */ t_ptr heap_extend(size_t words_nbr) { size_t size; t_ptr new_block; size = (words_nbr % 2 ? words_nbr + 1: words_nbr) * WORD_SIZE; if ((new_block = sbrk(size)) == NULL) return (NULL); SET(GET_HEAD(new_block), PACK(size, 0)); SET(GET_FOOT(new_block), PACK(size, 0)); SET(GET_HEAD(GET_NEXT(new_block)), PACK(0, 1)); return (heap_merge(new_block)); }
/* removes the element of minimum weight or does nothing in case of empty heap */ heap heap_remove_min(heap h) { if( h->root == NULL ) return NULL; tree sl = h->root->left; tree sr = h->root->right; free(h->root); h->root = sl; heap tmph = heap_create(h->f); tmph->root = sr; h = heap_merge(h, tmph); // free(tmph); return h; }
/* insert an element in the heap or NULL if object is NULL */ heap heap_insert(heap h, void* object) { if( object == NULL) return NULL; tree nt = malloc(sizeof(*nt)); nt->left = NULL; nt->right = NULL; nt->object = object; heap tmph = heap_create(h->f); tmph->root = nt; h = heap_merge(h, tmph ); // free(tmph); return h; }
/* ** Free ... ** - set the "reserved" boolean at 0 ** - defrag from the current block */ void free(void *ptr) { t_ptr block; size_t size; if (ptr) { block = (t_ptr)ptr; assert(IS_B_ALLOC(block)); size = GET_B_SIZE(block); SET(GET_HEAD(block), PACK(size, 0)); SET(GET_FOOT(block), PACK(size, 0)); heap_merge(block); } }