This commit is contained in:
Timothy Warren 2019-04-30 16:15:45 -04:00
parent cd4c6002c6
commit 47d569e3fc

31
db.c
View File

@ -352,6 +352,34 @@ Cursor* leaf_node_find(Table* table, uint32_t page_num, uint32_t key) {
return cursor; 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. * Return the position of the given key.
* If the key is not present, return the position * 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) { if (get_node_type(root_node) == NODE_LEAF) {
return leaf_node_find(table, root_page_num, key); return leaf_node_find(table, root_page_num, key);
} else { } else {
printf("Need to implement searching an internal node\n"); return internal_node_find(table, root_page_num, key);
exit(EXIT_FAILURE);
} }
} }