function insert(tree: BTree, key: number) { if (tree.root.keys.length === MAX_KEYS) {const oldRoot = tree.root;
tree.root = { keys: [], children: [oldRoot], leaf: false };splitChild(tree.root, 0);
}
insertNonFull(tree.root, key);
}
function insertNonFull(node: BNode, key: number) {let index = node.keys.length - 1;
if (node.leaf) {while (index >= 0 && key < node.keys[index]) index--;
node.keys.splice(index + 1, 0, key);
return;
}
while (index >= 0 && key < node.keys[index]) index--;
index++;
if (node.children[index].keys.length === MAX_KEYS) {splitChild(node, index);
if (key > node.keys[index]) index++;
}
insertNonFull(node.children[index], key);
}
Order 4 B-tree: each node holds 1 to 3 keys. Start with an empty root.
Understanding B-tree
The idea
A B-tree keeps many keys per node, sorted, with one child between each pair of neighbouring keys. Every node except the root holds between t − 1 and 2t − 1 keys, and all leaves sit at the same depth, so the tree is always balanced and very shallow: with t = 64 three levels index millions of keys.
Insertion walks down to a leaf and drops the key in its sorted place. To make room ahead of time, any full node met on the way is split: its middle key moves up into the parent and the two halves become separate children. Splitting the root is the only way the tree gets taller, and it grows from the top.
The four stages
Complexity
Versus its siblings
Pseudocode
INSERT(tree, key)
if the root is full: make a new root above it and SPLIT the old root
INSERTNONFULL(root, key)
INSERTNONFULL(node, key)
if node is a leaf: put key in its sorted place
else: child ← the child between the keys around key
if child is full: SPLIT it, the middle key moves up; pick the correct half
INSERTNONFULL(child, key)
When to use
Pitfalls
History
Rudolf Bayer and Edward McCreight designed the B-tree at Boeing in 1970 for indexes too large for memory; the B has never been officially explained, with Boeing, balanced and Bayer all offered. The B+ tree, which keeps data only in linked leaves, is the form most databases use today.