TExcelTAD
Home › Advanced & Succinct Data Structures › The van Emde Boas Layout for Search Trees

The van Emde Boas Layout for Search Trees

A B-tree searches in O(log⁡BN)O(\log_B N) I/Os because its nodes are exactly one block wide. Without knowing BB, 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 O(log⁡BN)O(\log_B N) blocks for every BB.

The layout

Take a complete binary tree of height hh (levels 11 to hh, N=2h−1N = 2^h - 1 nodes). Cut it at the middle level:

  • the top tree: the upper ⌊h/2⌋\lfloor h/2 \rfloor levels, a complete tree with about N\sqrt{N} nodes;
  • the bottom trees: the subtrees hanging below it, about N\sqrt{N} of them, each of height ⌈h/2⌉\lceil h/2 \rceil with about N\sqrt{N} 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.

text
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 contiguously

The program prints the layout of a tree of height 4 (nodes numbered as in a heap: root 1, children of ii are 2i2i and 2i+12i + 1), then compares the blocks touched by searches in three layouts of a tree with 218−12^{18} - 1 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.

python · try it yourself
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 {4,8,9}\{4, 8, 9\}, {5,10,11}\{5, 10, 11\}, {6,12,13}\{6, 12, 13\}, {7,14,15}\{7, 14, 15\}. In the large experiment the sorted and BFS layouts both pay about lg⁡N−lg⁡B\lg N - \lg B blocks, while the vEB layout stays within a small factor of log⁡BN\log_B N for every BB from 4 to 1024. The code never mentions BB.

Why a search touches O(log⁡BN)O(\log_B N) blocks

Fix any BB. Follow the recursion of the layout down to the first level at which the pieces (top trees and bottom trees) have at most BB nodes. Those pieces have height kk with 2k−1≤B2^k - 1 \le B, and since the previous level's pieces had more than BB nodes and the height at most halves per level, k≥12lg⁡Bk \ge \frac{1}{2} \lg B roughly.

  • Each piece is stored contiguously and has at most BB nodes, so it occupies at most 2 blocks (it may straddle a block boundary).
  • A root-to-leaf path of length h=lg⁡(N+1)h = \lg (N + 1) passes through pieces of height kk one after another, so it visits at most h/k+1≤2lg⁡Nlg⁡B+1h / k + 1 \le \frac{2 \lg N}{\lg B} + 1 pieces.

Multiplying, a search touches at most about

2⋅2lg⁡Nlg⁡B=4log⁡BN blocks2 \cdot \frac{2 \lg N}{\lg B} = 4 \log_B N \text{ blocks}

which is O(log⁡BN)O(\log_B N), optimal up to the constant. The bound holds for every BB simultaneously, so it holds for every level of the memory hierarchy at once. The measured values above, between 1.2 and 1.5 times log⁡BN\log_B N, 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 BB the first level whose pieces fit in a block, and computes the resulting bound on the blocks a search can touch.

python · try it yourself
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}")
            break
tree 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 log⁡BN\log_B N: the analysis's 4log⁡BN4 \log_B N, 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 220−12^{20} - 1 keys. The keys 0,2,4,…0, 2, 4, \ldots 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.

cpp · try it yourself
#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, O(lg⁡2N)O(\lg^2 N) amortized moves per insert, O(lg⁡2NB)O(\frac{\lg^2 N}{B}) amortized I/Os), and a static vEB-layout tree over the array is updated along with it. The result supports search in O(log⁡BN)O(\log_B N) I/Os and insertions and deletions in O(log⁡BN+lg⁡2NB)O(\log_B N + \frac{\lg^2 N}{B}) amortized I/Os, which is O(log⁡BN)O(\log_B N) when B=Ω(lg⁡Nlg⁡lg⁡N)B = \Omega(\lg N \lg \lg N). Brodal, Fagerberg and Jacob (2002) gave a simpler version.

Layout Blocks per search Needs BB?
sorted array, binary search lg⁡N−lg⁡B+O(1)\lg N - \lg B + O(1) no
BFS (Eytzinger) lg⁡N−lg⁡B+O(1)\lg N - \lg B + O(1) no
B-tree nodes of BB keys log⁡B+1N+O(1)\log_{B+1} N + O(1) yes
van Emde Boas at most about 4log⁡BN4 \log_B N 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 hh stored in the van Emde Boas layout?

  1. Level by level
  2. In sorted order
  3. The top tree of the upper half of the levels first, then each bottom tree contiguously, all recursively
  4. Leaves first, then the root

In the analysis, why does each recursive piece with at most BB nodes cost at most 2 block transfers?

  1. Because it is cached
  2. Because it is stored contiguously, so it spans at most two blocks
  3. Because BB is a power of 2
  4. Because the tree is complete

Why does the vEB layout give O(log⁡BN)O(\log_B N) for every BB at once?

  1. Because it chooses BB automatically at run time
  2. Because for any BB there is a level of the recursion whose pieces have between about B\sqrt{B} and BB nodes, and the analysis uses that level, which the layout contains whatever BB is
  3. Because it is a B-tree
  4. It does not; it needs BB