void balance_children(size_t i, binary_heap_t* bheap) { size_t mc; size_t rc = getRChildIndex(i); size_t lc = getLChildIndex(i); if (lc >= bheap->filled_elements) return; if (rc < bheap->filled_elements) { if (bheap->value_comparer(bheap->buffer[rc], bheap->buffer[lc]) < 0) mc = rc; else mc = lc; } else mc = lc; if (bheap->value_comparer(bheap->buffer[mc], bheap->buffer[i]) < 0) { void* value = bheap->buffer[mc]; bheap->buffer[mc] = bheap->buffer[i]; bheap->buffer[i] = value; balance_children(mc, bheap); } }
void insert_binary_heap(void* value, binary_heap_t* bheap) { if (bheap->filled_elements == 0) { bheap->filled_elements = 1; bheap->buffer[0] = value; return; } if (bheap->filled_elements < bheap->max_size) { bheap->buffer[bheap->filled_elements] = value; bheap->filled_elements++; balance_heap(bheap); return; } if (bheap->value_comparer(bheap->buffer[0], value) < 0) { bheap->buffer[0] = value; balance_children(0, bheap); } }
int balance_children(item** root_address, int (*cmp_fn)(item*, item*)){ /* * Recursively balances all children under the root */ item* move = *root_address; if(!move) return 1; int im_c = imbalanced_p(move); if(im_c != 0){ balance(&move, cmp_fn); } int im_l = imbalanced_p(move->left); int im_r = imbalanced_p(move->right); if(im_l == 0 && im_r == 0) return 1; return (balance_children(&(move->right), cmp_fn) + balance_children(&(move->left), cmp_fn)); }
void* pop_binary_heap(binary_heap_t* bheap) { void* value = NULL; if (bheap->filled_elements <= 0) return NULL; value = bheap->buffer[0]; bheap->buffer[0] = bheap->buffer[bheap->filled_elements - 1]; bheap->filled_elements--; balance_children(0, bheap); return value; }
int balance_tree(item** root_address, int (*cmp_fn)(item*, item*)){ balance(root_address, cmp_fn); balance_children(root_address, cmp_fn); return 1; }