From 47d569e3fc762a437674e0a854cd235c6e005924 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Tue, 30 Apr 2019 16:15:45 -0400 Subject: [PATCH] Step 11 --- db.c | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/db.c b/db.c index bbdff91..99363d1 100644 --- a/db.c +++ b/db.c @@ -352,6 +352,34 @@ Cursor* leaf_node_find(Table* table, uint32_t page_num, uint32_t key) { return cursor; } +Cursor* internal_node_find(Table* table, uint32_t page_num, uint32_t key) { + void* node = get_page(table->pager, page_num); + uint32_t num_keys = *internal_node_num_keys(node); + + /* Binary search to find index of child to search */ + uint32_t min_index = 0; + uint32_t max_index = num_keys; /* there is one more child than key */ + + while (min_index != max_index) { + uint32_t index = (min_index + max_index) / 2; + uint32_t key_to_right = *internal_node_key(node, index); + if (key_to_right >= key) { + max_index = index; + } else { + min_index = index + 1; + } + } + + uint32_t child_num = *internal_node_child(node, min_index); + void* child = get_page(table->pager, child_num); + switch (get_node_type(child)) { + case NODE_LEAF: + return leaf_node_find(table, child_num, key); + case NODE_INTERNAL: + return internal_node_find(table, child_num, key); + } +} + /* * Return the position of the given key. * If the key is not present, return the position @@ -364,8 +392,7 @@ Cursor* table_find(Table* table, uint32_t key) { if (get_node_type(root_node) == NODE_LEAF) { return leaf_node_find(table, root_page_num, key); } else { - printf("Need to implement searching an internal node\n"); - exit(EXIT_FAILURE); + return internal_node_find(table, root_page_num, key); } }