B-Trees

To find one key among a billion, a balanced binary tree reads 30 pages from disk. A B-tree with 4 KB pages reads at most 5. Each page holds hundreds of keys, so the tree is short.

Pick a tree and drag the number of keys. Press Race and watch each lane read one page per step. Then we build, piece by piece, the node rules, the height bound, the page size, search, split, merge and the B+ tree that databases use.

You need a little Python and binary search trees (a key per node, smaller keys left). We build the rest from zero.

Based on Chapter 18, B-Trees, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Amortized Analysis. Next: Fibonacci Heaps.

Race three trees to one key

1 billion

Worst-case pages on one root-to-leaf path, root included, nothing cached. The B-trees use 8-byte keys and pointers with a 24-byte page header (Chapter 3): t = 127 for 4 KB, t = 511 for 16 KB. The range runs from full pages to half-full pages. The 10 ms per read is an illustrative hard-disk figure.

Chapter 0

Pages, Not Comparisons

Price one search on a disk and see which cost decides the answer

You store a billion user records on disk. A user logs in and you must find one record by its ID. A balanced binary search tree finds it in 30 steps. That sounds fast.

Each step visits a different node, and each node sits in a different page. A page is the fixed block of bytes the disk reads in one go, often 4 KB. Reading one page from a hard disk takes about 10 ms. Thirty pages take 300 ms, for one login.

Price one search

Each bar is the time to find one key among a billion. Warm is time spent reading pages; grey is time spent comparing keys. Switch the memory.

Illustrative orders of magnitude: 100 ns per page in RAM, 100 µs on an SSD, 10 ms on a hard disk, 1 ns per comparison. Binary tree: 30 pages, 30 comparisons. B-tree with 4 KB pages: 5 pages, binary search of at most 8 comparisons in each.

Flip to Hard disk. The binary tree spends 300 ms on reads and 30 ns on comparisons. The B-tree makes more comparisons, 40, and still wins by 250 ms, because it reads 5 pages instead of 30. On a disk, comparisons are free and page reads are the whole bill.

So a B-tree packs hundreds of keys into each node and sizes each node to one page. Each read then picks one child out of hundreds, not one out of two. The tree gets short, and short means few reads.

The failure. Symptom: an index that was fast in tests turns slow once the data outgrows RAM. Measure: count page reads per query, not CPU time; the database's I/O statistics show it. Fix: a structure whose height, not its comparison count, is small.

The road

  1. The node rules: between t − 1 and 2t − 1 keys, one more child than keys.
  2. The height bound: why a billion keys need so few levels.
  3. One node, one page: pick t from the page size.
  4. Search: one page per level, binary search inside.
  5. Insert and split: split full pages on the way down.
  6. Delete and merge: fill thin pages on the way down.
  7. The B-tree workbench: insert and delete anything (the showcase).
  8. B+ trees and range scans: data in the leaves, leaves in a chain.
  9. Caching the top: why a real lookup reads one or two pages.
  10. The field guide: terms, numbers, code and the credit.
A binary tree and a B-tree both hold a billion keys on a hard disk. Why is the B-tree faster?

Chapter 1

The Node Rules

Fix one number t and read off how full every node may be

A node holds the keys 10, 20 and 30 in sorted order. Below it hang four children: one for keys under 10, one for 10 to 20, one for 20 to 30, one for keys over 30. The keys are signposts. A search reads them and takes one of the four roads.

| 10 | 20 | 30 | / | | \ <10 10..20 20..30 >30

CLRS controls every node with one number, the minimum degree t, an integer of at least 2. Call the number of keys in a node k and its number of children c. Every node except the root obeys:

Say it aloud

t minus one is at most k, which is at most two t minus one; and c equals k plus one.

t − 1
t minus one the fewest keys a node may hold. t is the minimum degree, at least 2.
≤
is at most no larger than.
k
k the number of keys stored in this node.
2t − 1
two t minus one the most keys a node may hold. A node with this many is full.
c
c the children of an internal node: one road between and around each pair of keys.
In plain words

Pick t. Every node but the root keeps at least t − 1 keys and at most 2t − 1. An internal node with k keys has k + 1 children. The root may hold as few as 1 key.

With numbers

With t = 3, a node holds 2 to 5 keys and an internal node has 3 to 6 children. With t = 2, a node holds 1 to 3 keys: this is the 2-3-4 tree.

Fill one node

The boxes are the slots a node may use. Drag the keys up and down past both limits, then mark the node as the root.

3
3

Keys are illustrative multiples of 10.

Two more rules finish the definition. A node keeps its keys sorted, and every key in child i lies between the keys on either side of that road. And all leaves sit at the same depth. No other search tree in CLRS demands this; the B-tree keeps it by growing at the root, as Chapter 5 shows.

Why a lower limit? Without it, nodes could hold one key each, and the tree would be as tall as a binary tree. The floor keeps every non-root node about half full, and that caps the height.

The failure. Symptom: a hand-built tree passes every search test, then breaks on a delete. Measure: check every non-root node for k ≥ t − 1 and every leaf for the same depth. Fix: run that check after every operation while you debug.

In a B-tree with t = 4, how many keys can a non-root node hold?

Chapter 2

The Height Bound

Build the thinnest legal tree and count the keys it must hold

How tall can a B-tree with n keys get? Turn the question around. Build the tree of height h with the fewest keys the rules allow. If even that tree holds many keys, no tree of n keys can be tall. The height h counts the edges on a path from the root down to a leaf.

Build the thinnest tree

Each row is one level, with its fewest nodes. The root holds 1 key; every other node holds t − 1. Drag t and h.

3
2

Exact counts from the rules of Chapter 1. Wide rows draw the first nodes and print the count.

Count level by level. The root has 1 key, so it has at least 2 children. Each of those has at least t children, so level 2 has at least 2t nodes. Level 3 has at least 2t², and level h at least 2th−1. Below the root, every node holds at least t − 1 keys. Add it up, and the sum of the levels collapses:

1 + (t − 1)(2 + 2t + … + 2th−1) = 1 + 2(th − 1) = 2th − 1

The middle step uses the geometric sum: (t − 1) times (1 + t + … + th−1) equals th − 1. So any tree of height h holds at least that many keys. Call the number of keys n.

Say it aloud

n is at least two t to the h, minus one.

n
n the number of keys in the tree.
≥
is at least no smaller than.
2
two the root's two children, the fewest it may have.
th
t to the h t multiplied by itself h times: each level multiplies the node count by at least t.
In plain words

Raise t to the power h. Double it and subtract one. That is the fewest keys any tree of height h can hold, so the real n is at least that.

With numbers

With t = 3 and h = 2: 2 × 9 − 1 = 17 keys at least. The thinnest tree has a 1-key root, 2 nodes of 2 keys, and 6 leaves of 2 keys: 1 + 4 + 12 = 17.

Solve for h. Add one, halve, and take the logarithm base t:

Say it aloud

h is at most log base t of n plus one, over two.

h
h the height: edges from the root to any leaf.
≤
is at most h is a whole number, so round the right side down.
logt
log base t how many times you multiply by t to reach the number.
(n + 1)/2
n plus one, over two the key count with the root's doubling taken out.
In plain words

Add one to n and halve it. Ask how many times you must multiply by t to reach that. Round down. No tree of n keys is taller.

With numbers

With n = 1,000,000,000 and t = 127: (n + 1)/2 is 500,000,000, and log base 127 of that is 4.13. So h ≤ 4: at most 5 pages on any path. With t = 2 the same n allows h = 28.

tLargest h, n = 106Largest h, n = 109
2 (2-3-4 tree)1828
31118
127 (4 KB page)24
511 (16 KB page)23

The failure. Symptom: a capacity plan says "log n levels" and buys too little cache. Measure: use log base t, not base 2, and round down. Fix: plan with the bound for the worst case and with full nodes for the best.

A B-tree with t = 3 has height 2. What is the fewest keys it can hold?

Chapter 3

One Node, One Page

Fit keys and child pointers into a page and read off t

A disk does not read one key. It reads a whole page, so a node should fill exactly one page: every byte of that read then helps the search. In a real index, a child pointer is not a memory address. It is a page number, and following it means one disk read.

Call the page size P bytes, the key size sk and the pointer size sp. The header H is the fixed bytes that describe the page itself. A node with k keys stores k keys and k + 1 pointers. It must fit:

Say it aloud

k times s-k, plus k plus one times s-p, plus H, is at most P.

k
k the keys in one node; we want the largest k that fits.
sk
s-k the bytes per key, 8 for a 64-bit integer.
sp
s-p the bytes per child pointer (a page number), 8 here.
H
H the page header in bytes, 24 in our example.
P
P the page size in bytes, such as 4,096.
In plain words

Add the bytes of k keys, k + 1 pointers and the header. Raise k until the total passes P. The last k that fits is the most keys a page can hold.

With numbers

With P = 4,096, sk = sp = 8 and H = 24: 16k + 32 ≤ 4,096, so k ≤ 254. A full node has 2t − 1 keys, an odd number, so t = 127 and a node holds at most 253 keys and 254 children.

Pack one page

The bar is one page. Grey is the header, warm the keys, blue the pointers. The dim end holds nothing. Change the page and the key size.

Pointers are 8 bytes and the header is 24 bytes, both illustrative. Real pages also store record offsets and free space; the formula keeps only what sets t.

Bigger keys mean fewer keys per page, a smaller t and a taller tree. A 32-byte key in a 4 KB page gives t = 51 and up to 5 levels below the root for a billion keys. This is why indexes on long strings are slower than indexes on integers.

The failure. Symptom: an index on a long text column is much deeper than one on an integer ID. Measure: divide the page size by the bytes per key plus pointer. Fix: index a shorter key, such as a fixed-size ID or a prefix.

With 8-byte keys and pointers and a 24-byte header, a 4 KB page fits at most 254 keys. Why is t = 127 and not 127.5 or 128?

Chapter 4

Search

Read one page per level and pick the road inside it

Look for 45 in the tree below (t = 3). Read the root, [50]: 45 is smaller, so take road 0. Read [20, 35]: 45 is larger than both, so take road 2. Read the leaf [40, 45]: found. Three pages.

Step a search

Pick a key and press Step. Each warm page is one disk read; the teal mark shows where the scan stopped. Try a missing key.

45

A toy tree with t = 3 and 17 keys: the thinnest tree of height 2 from Chapter 2. The device scans each page left to right, as CLRS does.

Inside a page, the search finds the first key that is not smaller than the target. If it equals the target, stop. If the page is a leaf, the key is missing. Otherwise read the child on that road and repeat. CLRS scans left to right; a real index uses binary search inside the page.

How many pages does a search read? Call the depth of the page where it stops d: the edges from the root to it. Call the pages read R.

Say it aloud

R equals d plus one, which is at most h plus one.

R
R the pages a search reads, one per level it visits.
d
d the depth of the page where the search stops: found, or a leaf with no match.
+ 1
plus one the root, at depth 0, is a page too.
h
h the height of the tree.
In plain words

Count the edges from the root to the page where the search stops, and add one for the root. That is R. Every leaf sits at depth h, so a miss always reads h + 1 pages.

With numbers

45 stops in a leaf at d = 2, so R = 3. 50 stops at the root, d = 0, so R = 1. A missing 47 reads all 3 pages, h + 1 with h = 2.

pythondef search(x, k):                 # x: a node with .keys, .kids, .leaf
    while True:
        i = bisect_left(x.keys, k)     # first key >= k, binary search in the page
        if i < len(x.keys) and x.keys[i] == k:
            return x, i                # found
        if x.leaf:
            return None                # missing
        x = disk_read(x.kids[i])      # one page read per level

The CPU work is small. With binary search, each page of 253 keys costs at most 8 comparisons. CLRS counts the left-to-right scan as O(t) per page, O(t logt n) in total. The page reads are O(logt n).

The failure. Symptom: a lookup is slow although the tree is short. Measure: profile the time inside one page. Fix: a linear scan of 1,021 keys is wasteful; switch to binary search inside the page.

A B-tree has height 3. A search for a key that is not in the tree reads how many pages?

Chapter 5

Insert and Split

Split every full page on the way down, so the leaf always has room

A new key always goes into a leaf. A binary tree hangs a new leaf below the old one, but that would put one leaf deeper than the others. So the key goes into an existing leaf. If that leaf is full, it must split.

A split takes a full node of 2t − 1 keys. The middle key, the median, moves up into the parent. The keys left of it stay; the keys right of it move to a new node.

Say it aloud

Two t minus one equals t minus one, plus one, plus t minus one.

2t − 1
two t minus one the keys in the full node before the split.
(t − 1)
t minus one the keys that stay in the old node, the left half.
1
one the median, which moves up into the parent.
(t − 1)
t minus one the keys that move to the new node, the right half.
In plain words

Take the middle key of a full node up to the parent. Each half keeps t − 1 keys, exactly the minimum, so both halves are legal.

With numbers

With t = 3 the full node [10, 20, 30, 40, 50] splits into [10, 20], the median 30 and [40, 50]: 5 = 2 + 1 + 2. The parent gains one key and one child.

The parent gains a key, so it must not be full. CLRS makes sure of that with one trick: on the way down, split every full node you meet, before you enter it. The parent of any split is then never full. When the insert reaches the leaf, the leaf has room. One pass down, never back up.

Insert, split, repeat

Press Step to run each insert one move at a time. Red is a full page about to split; purple is the median moving up.

t = 3, keys 10, 20, 30, 40, 50, 60, 70, 80, 5, 15, 90. Page counts: every page touched is a read, every page changed is a write; pages made in this insert are not read.

Watch three moments. Inserting 60 finds the root full, so the root splits and 30 becomes a new root: the tree grows one level, at the top. Inserting 80 fills the right leaf but does not split it; only the next visit will. Inserting 90 meets that full leaf on the way down and splits it, and 60 moves up beside 30.

The only way the tree grows taller is a root split. A new level appears above all the leaves at once, so all leaves stay at the same depth. A split writes 3 pages: the old node, the new node and the parent.

The failure. Symptom: inserts of sorted keys leave the pages half empty and the index twice its size. Measure: divide the keys by the slots in all pages. Fix: load sorted data with a bulk load, which fills pages in order, instead of inserting one key at a time.

Why does CLRS split full nodes on the way down instead of after the insert?

Chapter 6

Delete and Merge

Make every page you enter hold at least t keys, so a removal never leaves it too thin

Delete mirrors insert. Insert must never enter a full page. Delete must never enter a page with only t − 1 keys, because removing one key would break the floor. So on the way down, CLRS tops up every thin child before it enters. The one exception is the root.

There are three cases, named by where the key is.

CaseWhere the key isWhat to do
1in a leafremove it; the descent made sure the leaf has at least t keys
2ain an internal page, left child has ≥ t keysreplace it by its predecessor (largest key on the left), then delete that key below
2bin an internal page, right child has ≥ t keysreplace it by its successor (smallest key on the right), then delete that key below
2cin an internal page, both children have t − 1merge: left child + key + right child become one page of 2t − 1 keys, then delete from it
3abelow; the next child has t − 1, a sibling has ≥ trotate: a parent key moves down into the child, a sibling key moves up
3bbelow; the next child and its siblings have t − 1merge the child with a sibling, pulling the parent key down between them

Step each delete case

Pick a case and press Step. Teal is the key to delete; purple marks the pages that change.

Toy trees with t = 3, so every non-root page holds 2 to 5 keys. Rotations check the left sibling first.

Follow case 3a. Delete 40 from root [30, 60] over leaves [10, 20, 25], [40, 50], [70, 80]. The leaf [40, 50] has 2 keys, the minimum, and its left sibling has 3. So 30 moves down into the leaf and 25 moves up into the root: root [25, 60], leaf [30, 40, 50]. Now case 1 removes 40, leaving [30, 50].

Follow case 3b. Delete 50 from root [30] over [10, 20] and [40, 50]. Both children hold 2 keys. Merge them with 30 between: 2 + 1 + 2 = 5 keys, the split equation run backwards. The root is now empty, so the merged page becomes the root and the tree is one level shorter. Trees grow at the root and shrink at the root.

The failure. Symptom: after many deletes, a check finds a page with fewer than t − 1 keys. Measure: run the node-rule check after every delete in a random test. Fix: the code removed a key and then tried to repair upward; top up each child before you enter it instead.

You delete a key from an internal page. Both children beside it hold exactly t − 1 keys. What happens?

Chapter 7

The B-Tree Workbench

Insert and delete any key, change t, and watch the height, the fill and the page counts

Here is the whole tree, with the insert of Chapter 5 and the delete of Chapter 6 running live. Every operation reports the pages it read and wrote and the case it used.

Build and break a B-tree

Type a key from 1 to 99 and press Insert or Delete, or use the presets. Changing t starts a fresh tree.

height0
keys0
pages1
fill0%

Keys 1 to 99, at most 20 in the tree on a phone and 48 on a wider screen, so the keys stay legible. Fill is the keys stored divided by the 2t − 1 slots of every page.

Try three things. Insert 1 to 20 with t = 2 and count the root splits as the height climbs. Then switch to t = 4 and do the same: fewer, wider pages and a shorter tree. Then delete keys until the root empties and the height drops.

Watch the fill. Sorted inserts always split the rightmost leaf, and every split leaves a half-full page behind. In our simulation of 20,000 inserts with t = 50, sorted keys filled 50% of the slots and random keys filled 70%. Sorted keys also split once per t − 1 inserts, here one split per 49.

OperationPages readPages written
Searchat most h + 10
Insert, no splith + 11
Insert with s splitsh + 13s + 1 at most
DeleteO(h), siblings includedO(h)

The failure. Symptom: an index that only grows by appending keys, such as timestamps, is twice the size of the data's need. Measure: the fill reading of the workbench after Insert 1 to 20. Fix: fill pages fully when keys arrive in order; real systems add a rule for rightmost inserts.

With t = 3, you insert keys in sorted order. About what share of the page slots ends up used?

Chapter 8

B+ Trees and Range Scans

Keep records only in the leaves, chain the leaves, and a range becomes one descent and a walk

A query asks for every order placed between 10:00 and 10:05. That is a range query: find the first key, then every key after it until the end. In a CLRS B-tree the keys of a range are spread over leaves and internal pages, so the walk climbs up and down.

A B+ tree changes two things. Records live only in the leaves; internal pages hold only keys and child pointers, as signposts. And each leaf points to the next leaf, a leaf chain. When a leaf splits, a copy of its middle key goes up and the key itself stays in the leaf.

Scan a range two ways

Drag the range ends. Pink keys are the answer; warm pages are read. Switch trees and compare the counts.

6
18

Toy trees with the 12 keys 2, 4, ..., 24. The B+ tree has 4 leaves of 3 keys and two internal levels. The B-tree has t = 2; we insert the keys in a fixed shuffled order.

Count the pages of a B+ range scan. Call the internal levels above the leaves d, the leaves the range touches ℓ, the keys returned m and the keys per leaf L.

Say it aloud

R equals d plus ell, and ell is at most the ceiling of m over L, plus one.

R
R the pages the range scan reads.
d
d the internal pages on the one descent to the first leaf.
ℓ
ell the leaves the range touches, read one after another along the chain.
⌈m/L⌉
the ceiling of m over L m keys divided by L keys per leaf, rounded up.
+ 1
plus one the range can start in the middle of a leaf and spill into one more.
In plain words

Descend once through d internal pages to the leaf of the first key. Then walk the chain, one page per leaf, until a key passes the end. R is the descent plus the leaves.

With numbers

In the toy, the range 6 to 18 returns m = 7 keys with L = 3 and d = 2. The keys sit in 3 leaves, so R = 2 + 3 = 5 pages; the bound allows ℓ up to 3 + 1 = 4. With d = 3 and L = 200, a scan of 10,000 rows reads at most 3 + 51 = 54 pages.

The descent is paid once, and the rest is reading leaves in key order. B+ internal pages also hold more keys, because they carry no record data. Take our 4 KB example. A B-tree that stores an 8-byte record pointer beside each key fits 169 keys per page. A B+ internal page fits 254.

The failure. Symptom: a range query on a large table reads far more pages than rows it returns. Measure: compare pages read with ⌈m/L⌉. Fix: make sure the query uses the ordered index and scans its leaves, not a fresh descent per row.

Why is a range scan cheap in a B+ tree?

Chapter 9

Caching the Top

Keep the small upper levels in RAM and pay disk reads only near the leaves

Every lookup reads the root. Most lookups read the same few pages just below it. So a database keeps recently used pages in RAM, in a buffer pool, and reads from disk only on a miss. CLRS makes the same assumption for the root: it is always in memory.

The levels grow fast going down, so the top ones are cheap to keep. Take a B+ tree of a billion records, 200 records per leaf and 200 children per internal page, with 4 KB pages. From the bottom: 5,000,000 leaves, then 25,000 pages, then 125, then the root.

Cache the top levels

Each bar is one level, wider for more pages (log scale). Blue levels sit in RAM. Drag the levels to cache and the size of the table.

1 billion
2

Illustrative B+ tree: 200 records per leaf, 200 children per internal page, 4 KB pages. Real fan-outs depend on key size and fill.

Call the levels cached c. The disk reads left for one lookup are

Say it aloud

R equals h plus one, minus c.

R
R the pages a lookup must read from disk.
(h + 1)
h plus one the levels of the tree, root to leaves, one page each on a lookup.
c
c the upper levels kept whole in the buffer pool.
In plain words

Count the levels. Subtract the levels kept in RAM. The rest each cost one disk read per lookup.

With numbers

The billion-record tree has h + 1 = 4 levels. Cache the root and the 125 pages below it, 126 pages or about 0.5 MB, and c = 2, so R = 2. Cache the 25,000-page level too, about 103 MB, and R = 1.

Page sizes vary by system, so the numbers shift. These come from each system's own documentation.

SystemPage sizeWhat its docs say about the tree
SQLite4,096 bytes by default since version 3.12.0table b-trees keep all data in the leaves; interior pages hold only keys and child pointers
PostgreSQLusually 8 kB; a build option can change itevery table and index is an array of fixed-size pages
MySQL InnoDB16 KB by default; 4, 8, 32 or 64 KB allowedevery tablespace uses pages of this size

The failure. Symptom: lookups slow down sharply once the data grows past a certain size. Measure: the buffer pool hit rate; a drop means an upper level no longer fits. Fix: give the buffer pool enough RAM to hold every internal level of the hot indexes.

A B+ tree has 4 levels. The root and the next level are in the buffer pool. How many disk reads does a lookup need?

Chapter 10

The Field Guide

Keep the terms, the numbers, the checks and the core code on one page

A B-tree trades comparisons for page reads. Each node fills one page and holds between t − 1 and 2t − 1 keys, so the height is at most logt((n + 1)/2). Insert splits full pages on the way down; delete tops up thin pages on the way down. Both make one pass, and the tree grows and shrinks only at the root.

Terms and numbers

TermMeaningNumber on this page
Minimum degree tt − 1 to 2t − 1 keys per non-root nodet = 3: 2 to 5 keys
Height boundn ≥ 2th − 1, so h ≤ logt((n + 1)/2)t = 127, n = 109: h ≤ 4
Page fitk·sk + (k + 1)·sp + H ≤ P4 KB, 8-byte keys: t = 127
SearchR = d + 1 ≤ h + 1 pages45 in the toy: 3 pages
Split2t − 1 = (t − 1) + 1 + (t − 1); writes 3 pages[10..50] to [10, 20], 30, [40, 50]
Mergethe split run backwards[10, 20] + 30 + [40, 50]
B+ range scanR = d + ℓ, ℓ ≤ ⌈m/L⌉ + 110,000 rows, L = 200: 54 pages at most
Cached levelsR = (h + 1) − c disk readsa billion records, 0.5 MB cached: 2 reads

Before you trust a B-tree

  1. Pick t from the page size and the key size, not from a guess.
  2. Check after every operation in tests: sorted keys, k + 1 children, key limits, all leaves at one depth.
  3. Split before you enter a full child; top up before you enter a thin child.
  4. Use binary search inside a page.
  5. Bulk load sorted data; do not insert it one key at a time.
  6. Size the buffer pool to hold every internal level of the hot indexes.

The core code

pythonclass Node:
    def __init__(self, leaf=True):
        self.keys, self.kids, self.leaf = [], [], leaf

class BTree:
    def __init__(self, t):
        self.t, self.root = t, Node()

    def split_child(self, x, i):          # x.kids[i] is full: 2t - 1 keys
        t, y = self.t, x.kids[i]
        z = Node(y.leaf)
        x.keys.insert(i, y.keys[t - 1])          # the median moves up
        z.keys, y.keys = y.keys[t:], y.keys[:t - 1]
        if not y.leaf:
            z.kids, y.kids = y.kids[t:], y.kids[:t]
        x.kids.insert(i + 1, z)

    def insert(self, k):
        r = self.root
        if len(r.keys) == 2 * self.t - 1:        # full root: grow at the top
            self.root = Node(leaf=False)
            self.root.kids.append(r)
            self.split_child(self.root, 0)
        x = self.root
        while not x.leaf:
            i = bisect_right(x.keys, k)
            if len(x.kids[i].keys) == 2 * self.t - 1:
                self.split_child(x, i)           # split before entering
                if k > x.keys[i]: i += 1
            x = x.kids[i]
        insort(x.keys, k)                        # the leaf has room

t = BTree(3)
for k in [10, 20, 30, 40, 50, 60, 70, 80, 5, 15, 90]: t.insert(k)
print(t.root.keys, [c.keys for c in t.root.kids])
# [30, 60] [[5, 10, 15, 20], [40, 50], [70, 80, 90]]

The code needs from bisect import bisect_right, insort. Delete follows the six cases of Chapter 6.

Keep going

The takeaway. On disk, count pages, not comparisons. Make each node one page, make the page hold hundreds of keys, and a billion keys sit a handful of reads away.
A red-black tree corresponds to which B-tree?

Now press Present or Teach. Derive the height bound from memory, size t for a 4 KB page, and walk one split and one merge. Then go back to the race and say why the 16 KB lane wins.

Source

T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 18, B-Trees. The rules, the height bound and the procedures follow the book.

R. Bayer and E. McCreight introduced B-trees in "Organization and Maintenance of Large Ordered Indices" (Acta Informatica, 1972). Page sizes come from the SQLite, PostgreSQL and MySQL documentation. The devices, toy trees, byte layouts and fill simulations are our own.

CLRS Chapter 18 · B-Trees
Next: Fibonacci Heaps · Back to Gleams