The van Emde Boas Layout for Search Trees
A B-tree searches in I/Os because its nodes are exactly one block wide. Without knowing , can a search tree still achieve that? Yes: keep an ordinary binary search tree, but store its nodes in memory in a recursive order, the van Emde Boas layout (Prokop, 1999; the name comes from the recursion of van Emde Boas trees, which split keys at half their bits in the same way). A root-to-leaf path then touches blocks for every .
The layout
Take a complete binary tree of height (levels to , nodes). Cut it at the middle level:
- the top tree: the upper levels, a complete tree with about nodes;
- the bottom trees: the subtrees hanging below it, about of them, each of height with about nodes.
Store the top tree first, laid out recursively, then each bottom tree, from left to right, each laid out recursively and contiguously. The recursion stops at single nodes.
VEB-LAYOUT(subtree T of height h)
1 if h == 1
2 output the root of T
3 else
4 VEB-LAYOUT(top tree of T: its upper floor(h/2) levels)
5 for each bottom tree S of T, left to right // the subtrees below the top tree
6 VEB-LAYOUT(S) // height ceil(h/2), stored contiguouslyThe program prints the layout of a tree of height 4 (nodes numbered as in a heap: root 1, children of are and ), then compares the blocks touched by searches in three layouts of a tree with keys: the sorted array (binary search), the level-by-level BFS layout (also called Eytzinger, used by std::priority_queue), and the vEB layout. The cache is cold for each search, so the count is the number of distinct blocks on the search path.
import math, random
def veb_order(root, h):
"""Heap indices (root = 1, children 2i, 2i + 1) of a complete subtree of height h, in vEB order."""
if h == 1:
return [root]
top_h = h // 2 # top tree: the upper half of the levels
bottom_h = h - top_h
order = veb_order(root, top_h)
first_leaf = root << (top_h - 1) # leaves of the top tree, left to right
for leaf in range(first_leaf, first_leaf + (1 << (top_h - 1))):
for child in (2 * leaf, 2 * leaf + 1):
order += veb_order(child, bottom_h) # each bottom tree is stored contiguously
return order
def inorder_rank(i, h): # key stored at heap index i of a complete BST
depth = i.bit_length() - 1
below = h - depth - 1 # height of the subtree under i, minus one
offset = i - (1 << depth) # position of i within its level
return (offset * 2 + 1) * (1 << below) - 1
h = 4
order = veb_order(1, h)
print("height 4, vEB order of heap indices:", order)
print("keys in memory order: ", [inorder_rank(i, h) for i in order])
def blocks_per_search(pos, h, B, queries):
total = 0
for x in queries:
i, blocks = 1, set()
while i < (1 << h): # walk down the complete BST
blocks.add(pos[i] // B)
k = inorder_rank(i, h)
if x == k: break
i = 2 * i + (x > k)
total += len(blocks)
return total / len(queries)
h = 18 # 2^18 - 1 keys
N = (1 << h) - 1
veb = veb_order(1, h)
pos_veb = [0] * (1 << h)
for p, i in enumerate(veb): pos_veb[i] = p
pos_bfs = list(range(-1, (1 << h) - 1)) # heap index i at position i - 1 (Eytzinger)
pos_sorted = [0] + [inorder_rank(i, h) for i in range(1, 1 << h)] # a sorted array
rng = random.Random(1999)
queries = [rng.randrange(N) for _ in range(1000)]
print(f"N = {N}: blocks touched per search (cold cache)")
for B in [4, 16, 64, 256, 1024]:
r = [blocks_per_search(p, h, B, queries) for p in (pos_sorted, pos_bfs, pos_veb)]
print(f"B = {B:4}: sorted {r[0]:5.2f} BFS {r[1]:5.2f} vEB {r[2]:5.2f} log_B N = {math.log(N, B):5.2f}")height 4, vEB order of heap indices: [1, 2, 3, 4, 8, 9, 5, 10, 11, 6, 12, 13, 7, 14, 15]
keys in memory order: [7, 3, 11, 1, 0, 2, 5, 4, 6, 9, 8, 10, 13, 12, 14]
N = 262143: blocks touched per search (cold cache)
B = 4: sorted 15.75 BFS 15.76 vEB 10.76 log_B N = 9.00
B = 16: sorted 13.93 BFS 13.95 vEB 6.28 log_B N = 4.50
B = 64: sorted 11.98 BFS 11.99 vEB 4.28 log_B N = 3.00
B = 256: sorted 9.99 BFS 10.01 vEB 3.30 log_B N = 2.25
B = 1024: sorted 8.00 BFS 8.02 vEB 2.25 log_B N = 1.80
In the height-4 example the top tree is nodes 1, 2, 3, then come the four bottom trees , , , . In the large experiment the sorted and BFS layouts both pay about blocks, while the vEB layout stays within a small factor of for every from 4 to 1024. The code never mentions .
Why a search touches blocks
Fix any . Follow the recursion of the layout down to the first level at which the pieces (top trees and bottom trees) have at most nodes. Those pieces have height with , and since the previous level's pieces had more than nodes and the height at most halves per level, roughly.
- Each piece is stored contiguously and has at most nodes, so it occupies at most 2 blocks (it may straddle a block boundary).
- A root-to-leaf path of length passes through pieces of height one after another, so it visits at most pieces.
Multiplying, a search touches at most about
which is , optimal up to the constant. The bound holds for every simultaneously, so it holds for every level of the memory hierarchy at once. The measured values above, between 1.2 and 1.5 times , show that the worst-case constant 4 is pessimistic.
The program makes the analysis concrete for a tree of height 18: it lists the piece heights at every level of the recursion, finds for each the first level whose pieces fit in a block, and computes the resulting bound on the blocks a search can touch.
import math
def piece_heights(h):
"""Heights of the pieces at each level of the vEB recursion (top and bottom parts)."""
levels, current = [], [h]
while max(current) > 1:
nxt = []
for x in current:
if x > 1: nxt += [x // 2, x - x // 2]
else: nxt.append(x)
levels.append(sorted(set(nxt)))
current = nxt
return levels
h = 18
levels = piece_heights(h)
print(f"tree height {h}: piece heights by recursion level:", levels)
for B in [16, 64, 256, 1024]:
for depth, hs in enumerate(levels):
if all(2 ** x - 1 <= B for x in hs): # first level whose pieces fit in one block
k = min(hs)
pieces = math.ceil(h / k)
print(f"B = {B:4}: level {depth + 1}, pieces of height {hs} (at most {2 ** max(hs) - 1} nodes); "
f"a path crosses at most {pieces} pieces -> at most {2 * pieces} blocks; log_B N = {h / math.log2(B):.2f}")
breaktree height 18: piece heights by recursion level: [[9], [4, 5], [2, 3], [1, 2], [1]]
B = 16: level 3, pieces of height [2, 3] (at most 7 nodes); a path crosses at most 9 pieces -> at most 18 blocks; log_B N = 4.50
B = 64: level 2, pieces of height [4, 5] (at most 31 nodes); a path crosses at most 5 pieces -> at most 10 blocks; log_B N = 3.00
B = 256: level 2, pieces of height [4, 5] (at most 31 nodes); a path crosses at most 5 pieces -> at most 10 blocks; log_B N = 2.25
B = 1024: level 1, pieces of height [9] (at most 511 nodes); a path crosses at most 2 pieces -> at most 4 blocks; log_B N = 1.80
The bounds (18, 10, 10 and 4 blocks) are between 2.2 and 4.4 times : the analysis's , up to rounding the number of pieces on a path up to a whole number. The measured averages above are well below them.
In C++
The layout and the search for keys. The keys are stored at their vEB positions by an in-order walk, and searches for random values (half of them present) navigate by heap index, reading keys from the vEB-ordered array.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <set>
#include <vector>
// Append the heap indices of the complete subtree (root, height h) in van Emde Boas order.
void veb_order(std::uint32_t root, int h, std::vector<std::uint32_t>& out) {
if (h == 1) { out.push_back(root); return; }
int top = h / 2, bottom = h - top;
veb_order(root, top, out);
std::uint32_t first_leaf = root << (top - 1);
for (std::uint32_t leaf = first_leaf; leaf < first_leaf + (1u << (top - 1)); ++leaf)
for (std::uint32_t child : {2 * leaf, 2 * leaf + 1}) veb_order(child, bottom, out);
}
int main() {
const int h = 20;
const std::uint32_t n = (1u << h) - 1;
std::vector<std::uint32_t> order;
veb_order(1, h, order);
std::vector<std::uint32_t> pos(1u << h);
for (std::uint32_t p = 0; p < order.size(); ++p) pos[order[p]] = p;
// Store the keys 0, 2, 4, ... (in-order) at their vEB positions.
std::vector<std::uint32_t> mem(n);
std::uint32_t next_key = 0;
auto fill = [&](auto&& self, std::uint32_t i) -> void { // in-order walk assigns keys
if (i > n) return;
self(self, 2 * i);
mem[pos[i]] = 2 * next_key++;
self(self, 2 * i + 1);
};
fill(fill, 1);
std::mt19937 rng(1999);
for (std::uint32_t B : {16u, 64u, 256u}) {
long blocks = 0, found = 0;
for (int q = 0; q < 2000; ++q) {
std::uint32_t x = rng() % (2 * n); // even values are keys
std::set<std::uint32_t> touched;
for (std::uint32_t i = 1; i <= n;) {
touched.insert(pos[i] / B);
std::uint32_t k = mem[pos[i]];
if (k == x) { ++found; break; }
i = 2 * i + (x > k);
}
blocks += static_cast<long>(touched.size());
}
std::printf("N = %u, B = %3u: %.2f blocks per search in the vEB layout (log_B N = %.2f), %ld hits\n",
n, B, blocks / 2000.0, std::log(double(n)) / std::log(double(B)), found);
}
}N = 1048575, B = 16: 7.48 blocks per search in the vEB layout (log_B N = 5.00), 1017 hits
N = 1048575, B = 64: 4.71 blocks per search in the vEB layout (log_B N = 3.33), 1017 hits
N = 1048575, B = 256: 3.80 blocks per search in the vEB layout (log_B N = 2.50), 947 hits
From static to dynamic
The vEB layout is static: inserting a key would require moving many nodes. Bender, Demaine and Farach-Colton (2000) built a cache-oblivious B-tree on top of it: the keys live in a packed memory array (a sorted array with gaps, rebalanced in windows, amortized moves per insert, amortized I/Os), and a static vEB-layout tree over the array is updated along with it. The result supports search in I/Os and insertions and deletions in amortized I/Os, which is when . Brodal, Fagerberg and Jacob (2002) gave a simpler version.
| Layout | Blocks per search | Needs ? |
|---|---|---|
| sorted array, binary search | no | |
| BFS (Eytzinger) | no | |
| B-tree nodes of keys | yes | |
| van Emde Boas | at most about | no |
Note: In practice the BFS layout with software prefetching is often the fastest in-memory search on modern CPUs, because the next few levels can be prefetched in parallel; the vEB layout wins when the data does not fit in RAM or when several levels of the hierarchy matter.
Test yourself
How is a tree of height stored in the van Emde Boas layout?
- Level by level
- In sorted order
- The top tree of the upper half of the levels first, then each bottom tree contiguously, all recursively
- Leaves first, then the root
In the analysis, why does each recursive piece with at most nodes cost at most 2 block transfers?
- Because it is cached
- Because it is stored contiguously, so it spans at most two blocks
- Because is a power of 2
- Because the tree is complete
Why does the vEB layout give for every at once?
- Because it chooses automatically at run time
- Because for any there is a level of the recursion whose pieces have between about and nodes, and the analysis uses that level, which the layout contains whatever is
- Because it is a B-tree
- It does not; it needs