TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › B-Tree Insertion with Proactive Splitting

B-Tree Insertion with Proactive Splitting

A BST grows downwards: a new key becomes a new leaf, one level deeper. A B-tree cannot do that, since all its leaves must stay at the same depth. Instead, a new key always goes into an existing leaf, and when a node overflows it splits into two half-full nodes, pushing its middle key up into the parent. The tree grows only when the root splits, which adds a new root above it: B-trees grow at the top.

The version in this lesson splits proactively: on the way down, it splits every full node it meets before entering it. Then a split never has to travel back up, and the whole insertion is a single downward pass, reading each node once, which is exactly what a disk-based structure wants. The definitions come from B-Trees: Definition, Height and Search.

Splitting a full child

A full node yy has 2t−12t - 1 keys. Splitting it around its median key y.keyt−1y.\textit{key}_{t-1} produces two nodes of t−1t - 1 keys each, the minimum allowed, and moves the median into the parent xx, between them. The parent gains one key and one child, so it must not be full itself, which proactive splitting guarantees.

text
           x: [ ... a   b ... ]                       x: [ ... a  m  b ... ]
                      |                  ==>                  /    \
       y: [ k0 .. k(t-2)  m  k(t) .. k(2t-2) ]     [k0 .. k(t-2)]  [k(t) .. k(2t-2)]

B-TREE-SPLIT-CHILD(x, i)               // x is not full, x.c[i] is full
1  y = x.c[i]
2  z = a new node with the last t - 1 keys of y (and its last t children, if y is internal)
3  m = y.key[t - 1]                    // the median
4  y keeps its first t - 1 keys (and first t children)
5  insert m into x at position i, and z as child i + 1 of x
6  DISK-WRITE(y), DISK-WRITE(z), DISK-WRITE(x)

The split takes O(t)O(t) CPU time and three disk writes, and it keeps every property: yy and zz have t−1t - 1 keys each, the median separates their ranges, and the leaves stay at the same depth because zz sits at the same level as yy.

Insertion

text
B-TREE-INSERT(T, k)
1  r = T.root
2  if r is full                         // 2t - 1 keys
3      s = a new node with no keys and r as its only child
4      T.root = s
5      B-TREE-SPLIT-CHILD(s, 0)          // the only way the height grows
6  x = T.root
7  while x is not a leaf
8      i = index of the child whose range contains k
9      DISK-READ(x.c[i])
10     if x.c[i] is full
11         B-TREE-SPLIT-CHILD(x, i)
12         if k > x.key[i]  i = i + 1    // the median moved up: pick the correct half
13     x = x.c[i]
14 insert k into the leaf x, keeping the keys sorted; DISK-WRITE(x)

Invariant: whenever the loop is at node xx, xx is not full. It holds for the root after lines 2 to 5, and line 11 makes sure that the child the loop moves to is not full either. So the leaf finally reached has room for kk, and every split has room in its parent.

Cost. One pass down the tree: O(h)=O(log⁡tn)O(h) = O(\log_t n) disk reads and writes, and O(t)O(t) CPU time per node for the splits and the key shifts, O(tlog⁡tn)O(t \log_t n) in total.

The Python implementation prints the same events as the animation: the root splits, the splits on the way down, and the leaf each key ends up in.

python · try it yourself
class BNode:
    __slots__ = ("keys", "c")
    def __init__(self, keys=None, c=None):
        self.keys, self.c = keys or [], c or []        # c is empty for a leaf

class BTree:
    def __init__(self, t, say=print):
        self.t, self.root, self.say, self.splits = t, BNode(), say, 0
    def full(self, x):
        return len(x.keys) == 2 * self.t - 1
    def split_child(self, x, i):
        t, y = self.t, x.c[i]
        m = y.keys[t - 1]
        z = BNode(y.keys[t:], y.c[t:])                  # the upper half
        y.keys, y.c = y.keys[:t - 1], y.c[:t]           # the lower half
        x.keys.insert(i, m)
        x.c.insert(i + 1, z)
        self.splits += 1
        return m
    def insert(self, k):
        if self.full(self.root):
            self.root = BNode([], [self.root])
            m = self.split_child(self.root, 0)
            self.say(f"root is full: split it, {m} moves up into a new root (height grows)")
        x = self.root
        while x.c:
            i = 0
            while i < len(x.keys) and k > x.keys[i]:
                i += 1
            if self.full(x.c[i]):
                m = self.split_child(x, i)
                self.say(f"  on the way down for {k}: child is full, split it, {m} moves up")
                if k > x.keys[i]:
                    i += 1
            x = x.c[i]
        i = 0
        while i < len(x.keys) and k > x.keys[i]:
            i += 1
        x.keys.insert(i, k)
        self.say(f"insert {k} into the leaf {x.keys}")

def levels(root):
    out, level = [], [root]
    while level:
        out.append("  ".join(str(x.keys) for x in level))
        level = [c for x in level for c in x.c]
    return out

b = BTree(2)
for k in [8, 3, 15, 1, 6, 11, 19, 4, 13, 17, 2, 9, 21, 5, 7]:
    b.insert(k)
print("\n".join(levels(b.root)))
insert 8 into the leaf [8]
insert 3 into the leaf [3, 8]
insert 15 into the leaf [3, 8, 15]
root is full: split it, 8 moves up into a new root (height grows)
insert 1 into the leaf [1, 3]
insert 6 into the leaf [1, 3, 6]
insert 11 into the leaf [11, 15]
insert 19 into the leaf [11, 15, 19]
  on the way down for 4: child is full, split it, 3 moves up
insert 4 into the leaf [4, 6]
  on the way down for 13: child is full, split it, 15 moves up
insert 13 into the leaf [11, 13]
root is full: split it, 8 moves up into a new root (height grows)
insert 17 into the leaf [17, 19]
insert 2 into the leaf [1, 2]
insert 9 into the leaf [9, 11, 13]
insert 21 into the leaf [17, 19, 21]
insert 5 into the leaf [4, 5, 6]
  on the way down for 7: child is full, split it, 5 moves up
insert 7 into the leaf [6, 7]
[8]
[3, 5]  [15]
[1, 2]  [4]  [6, 7]  [9, 11, 13]  [17, 19, 21]

Notice the second root split, at the insertion of 17: the root [3, 8, 15] was full, so it split before the search for 17 even started, although 17 itself would have fitted into the leaf [19] without any split. Proactive splitting sometimes splits a node that a lazier method would have left alone; the price buys the single pass.

Testing, and how often nodes split

The test inserts random keys into B-trees with t=2t = 2, 33 and 1010, checks all the B-tree properties after every 50 insertions, and counts the splits. A split creates one new node, and a B-tree with nn keys has at most about n/(t−1)n/(t - 1) nodes, so nn insertions make at most about n/(t−1)n/(t - 1) splits: less than one split per t−1t - 1 insertions, amortized.

python · try it yourself
import random

class BNode:
    __slots__ = ("keys", "c")
    def __init__(self, keys=None, c=None):
        self.keys, self.c = keys or [], c or []

class BTree:
    def __init__(self, t):
        self.t, self.root, self.splits = t, BNode(), 0
    def split_child(self, x, i):
        t, y = self.t, x.c[i]
        z = BNode(y.keys[t:], y.c[t:])
        x.keys.insert(i, y.keys[t - 1]); x.c.insert(i + 1, z)
        y.keys, y.c = y.keys[:t - 1], y.c[:t]
        self.splits += 1
    def insert(self, k):
        if len(self.root.keys) == 2 * self.t - 1:
            self.root = BNode([], [self.root]); self.split_child(self.root, 0)
        x = self.root
        while x.c:
            i = 0
            while i < len(x.keys) and k > x.keys[i]: i += 1
            if len(x.c[i].keys) == 2 * self.t - 1:
                self.split_child(x, i)
                if k > x.keys[i]: i += 1
            x = x.c[i]
        i = 0
        while i < len(x.keys) and k > x.keys[i]: i += 1
        x.keys.insert(i, k)

def check(b):
    """asserts every B-tree property; returns (keys in order, height, number of nodes)"""
    t, out, depths, nodes = b.t, [], set(), 0
    def walk(x, depth, root):
        nonlocal nodes
        nodes += 1
        assert len(x.keys) <= 2 * t - 1 and (root or len(x.keys) >= t - 1)
        if not x.c:
            depths.add(depth); out.extend(x.keys); return
        assert len(x.c) == len(x.keys) + 1
        for i, c in enumerate(x.c):
            walk(c, depth + 1, False)
            if i < len(x.keys): out.append(x.keys[i])
    walk(b.root, 0, True)
    assert len(depths) == 1 and out == sorted(out)
    return out, depths.pop(), nodes

rng = random.Random(41)
for t in [2, 3, 10]:
    b, keys = BTree(t), rng.sample(range(10 ** 6), 4000)
    for i, k in enumerate(keys, 1):
        b.insert(k)
        if i % 50 == 0:
            assert check(b)[0] == sorted(keys[:i])
    out, h, nodes = check(b)
    print(f"t = {t:2}: n = {len(out)}, height {h}, {nodes} nodes, {b.splits} splits "
          f"({b.splits / len(out):.3f} per insert, at most 1/(t-1) = {1 / (t - 1):.3f})")
t =  2: n = 4000, height 8, 2295 nodes, 2286 splits (0.572 per insert, at most 1/(t-1) = 1.000)
t =  3: n = 4000, height 5, 1253 nodes, 1247 splits (0.312 per insert, at most 1/(t-1) = 0.500)
t = 10: n = 4000, height 3, 312 nodes, 308 splits (0.077 per insert, at most 1/(t-1) = 0.111)

The counts fit together exactly: every split creates one new node, a root split also creates the new root, and there are hh root splits, so the number of nodes is 1+splits+h1 + \text{splits} + h (for t=2t = 2: 1+2286+8=22951 + 2286 + 8 = 2295).

In C++

The C++ B-tree keeps the nodes in a vector of structs with key and child vectors, and uses std::upper_bound to choose the child. It inserts 200,000 seeded random keys with t=16t = 16, checks the properties and compares the keys with std::set.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <random>
#include <set>
#include <vector>

class BTree {
    struct Node { std::vector<int> keys, c; };            // c holds child indices; empty for a leaf
    std::vector<Node> n_{Node{}};
    int root_ = 0, t_;
    bool full(int x) const { return static_cast<int>(n_[x].keys.size()) == 2 * t_ - 1; }
    void split_child(int x, int i) {
        int y = n_[x].c[i];
        Node z;
        z.keys.assign(n_[y].keys.begin() + t_, n_[y].keys.end());
        if (!n_[y].c.empty()) z.c.assign(n_[y].c.begin() + t_, n_[y].c.end());
        int median = n_[y].keys[t_ - 1];
        n_[y].keys.resize(t_ - 1);
        if (!n_[y].c.empty()) n_[y].c.resize(t_);
        n_.push_back(std::move(z));                       // may reallocate: use indices only
        int zi = static_cast<int>(n_.size()) - 1;
        n_[x].keys.insert(n_[x].keys.begin() + i, median);
        n_[x].c.insert(n_[x].c.begin() + i + 1, zi);
        ++splits;
    }
    void walk(int x, int depth, bool root, std::vector<int>& out, std::set<int>& depths) const {
        const Node& nd = n_[x];
        int k = static_cast<int>(nd.keys.size());
        if (k > 2 * t_ - 1 || (!root && k < t_ - 1)) throw "node size";
        if (nd.c.empty()) { depths.insert(depth); out.insert(out.end(), nd.keys.begin(), nd.keys.end()); return; }
        if (static_cast<int>(nd.c.size()) != k + 1) throw "child count";
        for (int i = 0; i <= k; ++i) {
            walk(nd.c[i], depth + 1, false, out, depths);
            if (i < k) out.push_back(nd.keys[i]);
        }
    }
public:
    long splits = 0;
    explicit BTree(int t) : t_(t) {}
    void insert(int k) {
        if (full(root_)) {
            n_.push_back(Node{{}, {root_}});
            root_ = static_cast<int>(n_.size()) - 1;
            split_child(root_, 0);
        }
        int x = root_;
        while (!n_[x].c.empty()) {
            int i = static_cast<int>(std::upper_bound(n_[x].keys.begin(), n_[x].keys.end(), k) - n_[x].keys.begin());
            if (full(n_[x].c[i])) {
                split_child(x, i);
                if (k > n_[x].keys[i]) ++i;
            }
            x = n_[x].c[i];
        }
        auto& keys = n_[x].keys;
        keys.insert(std::upper_bound(keys.begin(), keys.end(), k), k);
    }
    int checked_height(std::vector<int>& out) const {
        std::set<int> depths;
        walk(root_, 0, true, out, depths);
        if (depths.size() != 1) throw "leaf depths";
        return *depths.begin();
    }
    std::size_t nodes() const { return n_.size(); }
};

int main() {
    BTree b(16);
    std::set<int> ref;
    std::mt19937 rng(41);
    while (ref.size() < 200000) {
        int k = static_cast<int>(rng() % 100000000);
        if (ref.insert(k).second) b.insert(k);
    }
    std::vector<int> out;
    int h = b.checked_height(out);
    bool same = out == std::vector<int>(ref.begin(), ref.end());
    std::printf("t = 16, n = %zu: height %d, %zu nodes, %ld splits, same keys as std::set: %s\n",
                ref.size(), h, b.nodes(), b.splits, same ? "yes" : "no");
}
t = 16, n = 200000: height 3, 9441 nodes, 9437 splits, same keys as std::set: yes

With t=16t = 16 a node holds up to 31 keys, and 200,000 keys fit in a tree of height 3, against about 20 levels for a red-black tree on the same keys.

Test yourself

With t=3t = 3, a full node holds [10, 20, 30, 40, 50]. Which key moves up when it splits?

  1. 20
  2. 30
  3. 40
  4. 10

When does the height of a B-tree increase?

  1. whenever a leaf splits
  2. only when the root splits
  3. when a key is inserted into a full leaf
  4. after every tt insertions

Why does proactive splitting split full nodes on the way down, even when the new key might not need it?

  1. To keep the tree perfectly full
  2. So that every split has room in its parent, and the insertion needs only one downward pass with no going back up
  3. To make searches faster
  4. Because a full node cannot be read from disk