diff --git a/bp_tree.c b/bp_tree.c index 3c8eca4eaaaa50211d96827529784b65f9357553..bdd967ec92394cc61d3e01d95f20afccc057da6b 100644 --- a/bp_tree.c +++ b/bp_tree.c @@ -56,6 +56,14 @@ void bp_node_shift(node *nd, int index) { } } +void bp_node_shit_del(node *nd, int index) { + for (int i = index; i < M - 1; i++) { + nd->user[i] = nd->user[i + 1]; + nd->data[i] = nd->data[i + 1]; + } + nd->data[M - 1] = 0; +} + node *bp_split(node *nd) { node *new = bp_create_node(); /* @@ -289,6 +297,66 @@ node *bp_insert_val(node *tree, entry person) { return tree; } +// DELETE ---------------------------------------------------------- + +control bp_delete_from(node *nd, uint64_t key) { + control c = {.value = 0}; + for (int i = 0; i < M; i++) { + if (nd->data[i] == key) { + nd->data[i] = 0; + nd->count--; + if (i != M - 1 && nd->data[i + 1] != 0) { + bp_node_shit_del(nd, i); + } + if (i == 0) { + c.value = nd->data[0]; + } + } + } + return c; +} + +control bp_delete(node *nd, uint64_t key, int depth) { + control c; + if (bp_is_leaf(nd)) { + c = bp_delete_from(nd, key); + } else { + for (int i = 0; i < M; i++) { + if (nd->data[i] > key || nd->data[i] == 0) { + c = bp_delete(nd->childs[i], key, depth + 1); + break; + } + + // if a current key was deleted, we must replace it with the new key + if (c.value != 0 && depth != 0) { + for (int i = 0; i < M; i++) + if (nd->data[i] == key) + nd->data[i] = c.value; + + return c; + } + } + } + + if (c.value != 0) { + return c; + } + return CONST_CONTR; +} + +node *bp_delete_val(node *tree, char phone[11]) { + uint64_t hash_i = generate_key(phone); + + control c = bp_delete(tree, hash_i, 0); + + if (c.value != 0) { + for (int i = 0; i < M; i++) + if (tree->data[i] == hash_i) + tree->data[i] = c.value; + } + return tree; +} + // SEARCH ---------------------------------------------------------- entry bp_search_node(node *tree, uint64_t hash) {