Search code examples
calgorithmb-tree

Algorithm to find k-th key in a B-tree?


I'm trying to understand how I should think about getting the k-th key/element in a B-tree. Even if it's steps instead of code, it will still help a lot. Thanks

Edit: To clear up, I'm asking for the k-th smallest key in the B-tree.


Solution

  • Ok so, after a few sleepless hours I managed to do it, and for anyone who will wonder how, here it goes in pseudocode (k=0 for first element):

    get_k-th(current, k):
    
    for i = 0 to current.number_of_children_nodes
        int size = size_of_B-tree(current.child[i])
        if(k <= size-1)
            return get_k-th(current.child[i], k)
        else if(k == size && i < current.number_of_children_nodes)
            return current.key[i]
        else if (is_leaf_node(current) && k < current.number_of_children_nodes)
            return node.key[k]
        k = k - size - 1;
    
    return null
    

    I know this might look kinda weird, but it's what I came up with and thankfully it works. There might be a way to make this code clearer, and probably more efficient, but I hope it's good enough to help anyone else who might get stuck on the same obstacle as I did.