Funnelsort and the Tall-Cache Assumption
Multiway merge sort reaches the sorting bound by merging runs at once, a fan-in it can only choose if it knows and . Funnelsort (Frigo, Leiserson, Prokop and Ramachandran, 1999) achieves the same bound cache-obliviously. Its merging device, the funnel, is a binary merge tree whose buffers are sized and laid out by the same recursion as the van Emde Boas layout. This lesson describes the simpler lazy funnelsort of Brodal and Fagerberg (2002), runs it, and states the analysis without the full proof.
The algorithm
FUNNELSORT(A) // n = |A|
1 if n is at most a constant
2 sort A directly
3 else
4 split A into k = n^(1/3) pieces of n^(2/3) items each
5 FUNNELSORT each piece
6 merge the k sorted pieces with a k-funnelThe k-funnel
A -funnel is a complete binary tree with leaves (the input runs) and a root (the output). Every node is a binary merger, and every edge carries a buffer. The buffer sizes are defined recursively: cut the tree at the middle level into a top -funnel and bottom -funnels; the edges between them get buffers of size ; the top and bottom funnels are built the same way, recursively. In memory, the top funnel is stored first, then the middle buffers, then the bottom funnels, each contiguous: the vEB layout with buffers.
The lazy merging rule (Brodal and Fagerberg): to FILL a buffer, repeatedly move the smaller head of the two child buffers into it, and whenever a child buffer is empty (and its subtree is not exhausted), FILL that child buffer first, completely. The root's buffer is the output.
FILL(v) // fill the buffer above node v
1 while the buffer above v is not full
2 for each child c of v whose buffer is empty and not exhausted
3 FILL(c)
4 if both child buffers are empty mark v exhausted; return
5 move the smaller of the two child buffer heads into v's bufferThe program implements lazy funnels and funnelsort, checks the output, and counts how many times an element moves from one buffer to the next.
import math, random
class Buffer:
__slots__ = ("data", "head", "cap", "done")
def __init__(self, cap):
self.data, self.head, self.cap, self.done = [], 0, cap, False
def size(self): return len(self.data) - self.head
def pop(self):
x = self.data[self.head]; self.head += 1
if self.head > 64 and self.head * 2 > len(self.data): # compact now and then
self.data, self.head = self.data[self.head:], 0
return x
class Funnel:
"""Lazy k-funnel (Brodal and Fagerberg): a binary merge tree whose edges carry buffers whose
sizes follow the van Emde Boas recursion: the edges in the middle of a funnel of height h
get buffers of size about (2^h)^(3/2)."""
def __init__(self, runs):
k = len(runs)
self.h = max(1, math.ceil(math.log2(k)))
self.leaves = 1 << self.h
size = [0] * (2 * self.leaves) # size[v]: capacity of the buffer above node v
def assign(top, h): # subtree rooted at heap index top, height h
if h <= 1: return
t = h // 2 # top part: t levels of edges
for i in range(1 << t): # edges from the top part to the bottom parts
size[(top << t) + i] = math.ceil((1 << h) ** 1.5)
assign(top, t)
for i in range(1 << t):
assign((top << t) + i, h - t)
assign(1, self.h)
self.buf = [Buffer(max(1, size[v])) for v in range(2 * self.leaves)]
for i in range(self.leaves): # leaf buffers are the input runs themselves
b = self.buf[self.leaves + i]
b.data = list(runs[i]) if i < k else []
b.cap, b.done = len(b.data), True
self.moves = 0
def fill(self, v): # merge from v's children until v's buffer is full
out, left, right = self.buf[v], self.buf[2 * v], self.buf[2 * v + 1]
while out.size() < out.cap:
for c in (2 * v, 2 * v + 1):
if self.buf[c].size() == 0 and not self.buf[c].done and c < self.leaves:
self.fill(c)
if left.size() == 0 and right.size() == 0:
out.done = True; return
if right.size() == 0 or (left.size() and left.data[left.head] <= right.data[right.head]):
out.data.append(left.pop())
else:
out.data.append(right.pop())
self.moves += 1
def merge_all(self):
self.buf[1].cap = sum(self.buf[self.leaves + i].size() for i in range(self.leaves))
self.fill(1)
return self.buf[1].data[self.buf[1].head:]
def funnelsort(a, stats):
n = len(a)
if n <= 8:
return sorted(a)
k = max(2, math.ceil(n ** (1 / 3))) # split into about n^(1/3) pieces of n^(2/3)
size = math.ceil(n / k)
runs = [funnelsort(a[i:i + size], stats) for i in range(0, n, size)]
f = Funnel(runs)
out = f.merge_all()
stats["moves"] += f.moves
return out
rng = random.Random(2002)
for n in [1000, 5000, 20000]:
a = [rng.randrange(10 ** 6) for _ in range(n)]
stats = {"moves": 0}
assert funnelsort(a, stats) == sorted(a)
print(f"n = {n:5}: sorted correctly, {stats['moves'] / n:5.2f} buffer moves per element, lg n = {math.log2(n):5.2f}")n = 1000: sorted correctly, 9.00 buffer moves per element, lg n = 9.97
n = 5000: sorted correctly, 11.94 buffer moves per element, lg n = 12.29
n = 20000: sorted correctly, 14.00 buffer moves per element, lg n = 14.29
Every element climbs one buffer per level of each funnel it passes through, and the funnels along the recursion have levels, so the total is about moves per element: funnelsort does work, like any comparison sort. Its advantage is entirely in how the moves use the cache.
The buffers of a -funnel take space in total, which the next program computes from the recursion. That matters: a -funnel with fits in the cache entirely.
import math
def buffer_space(h):
"""Total buffer capacity of a funnel of height h (k = 2^h leaves), by the same recursion."""
if h <= 1:
return 0
t = h // 2
middle = (1 << t) * math.ceil((1 << h) ** 1.5) # 2^t edges between the top and the bottom parts
return middle + buffer_space(t) + (1 << t) * buffer_space(h - t)
for h in range(2, 13, 2):
k = 1 << h
s = buffer_space(h)
print(f"k = {k:4}: buffer space {s:>10}, k^2 = {k * k:>8}, ratio {s / k ** 2:5.2f}")k = 4: buffer space 16, k^2 = 16, ratio 1.00
k = 16: buffer space 336, k^2 = 256, ratio 1.31
k = 64: buffer space 4798, k^2 = 4096, ratio 1.17
k = 256: buffer space 71248, k^2 = 65536, ratio 1.09
k = 1024: buffer space 1083424, k^2 = 1048576, ratio 1.03
k = 4096: buffer space 17089086, k^2 = 16777216, ratio 1.02
In C++
The same lazy funnels and funnelsort with std::deque buffers, up to a million keys.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <deque>
#include <random>
#include <vector>
// Lazy k-funnel: a binary merge tree in heap order; buffer v sits above node v.
class Funnel {
int leaves;
std::vector<std::deque<int>> buf;
std::vector<std::size_t> cap;
std::vector<char> done;
void assign(int top, int h) {
if (h <= 1) return;
int t = h / 2;
for (int i = 0; i < (1 << t); ++i)
cap[(top << t) + i] = static_cast<std::size_t>(std::ceil(std::pow(double(1 << h), 1.5)));
assign(top, t);
for (int i = 0; i < (1 << t); ++i) assign((top << t) + i, h - t);
}
void fill(int v) {
auto& out = buf[v];
auto& l = buf[2 * v];
auto& r = buf[2 * v + 1];
while (out.size() < cap[v]) {
for (int c : {2 * v, 2 * v + 1})
if (buf[c].empty() && !done[c] && c < leaves) fill(c);
if (l.empty() && r.empty()) { done[v] = 1; return; }
bool take_left = r.empty() || (!l.empty() && l.front() <= r.front());
auto& src = take_left ? l : r;
out.push_back(src.front());
src.pop_front();
++moves;
}
}
public:
long moves = 0;
explicit Funnel(const std::vector<std::vector<int>>& runs) {
int h = std::max(1, static_cast<int>(std::ceil(std::log2(double(runs.size())))));
leaves = 1 << h;
buf.resize(2 * leaves); cap.assign(2 * leaves, 1); done.assign(2 * leaves, 0);
assign(1, h);
for (int i = 0; i < leaves; ++i) {
if (i < static_cast<int>(runs.size())) buf[leaves + i].assign(runs[i].begin(), runs[i].end());
done[leaves + i] = 1;
}
}
std::vector<int> merge_all() {
std::size_t total = 0;
for (int i = 0; i < leaves; ++i) total += buf[leaves + i].size();
cap[1] = total;
fill(1);
return {buf[1].begin(), buf[1].end()};
}
};
std::vector<int> funnelsort(const std::vector<int>& a, long& moves) {
if (a.size() <= 8) { auto b = a; std::sort(b.begin(), b.end()); return b; }
std::size_t k = std::max<std::size_t>(2, static_cast<std::size_t>(std::ceil(std::cbrt(double(a.size())))));
std::size_t size = (a.size() + k - 1) / k;
std::vector<std::vector<int>> runs;
for (std::size_t i = 0; i < a.size(); i += size)
runs.push_back(funnelsort(std::vector<int>(a.begin() + i, a.begin() + std::min(a.size(), i + size)), moves));
Funnel f(runs);
auto out = f.merge_all();
moves += f.moves;
return out;
}
int main() {
std::mt19937 rng(2002);
for (int n : {1000, 100000, 1000000}) {
std::vector<int> a(n);
for (auto& x : a) x = static_cast<int>(rng() % 1000000000);
long moves = 0;
auto s = funnelsort(a, moves);
std::sort(a.begin(), a.end());
std::printf("n = %7d: %s, %.2f buffer moves per element, lg n = %.2f\n",
n, s == a ? "sorted" : "WRONG", double(moves) / n, std::log2(double(n)));
}
}n = 1000: sorted, 9.00 buffer moves per element, lg n = 9.97
n = 100000: sorted, 15.02 buffer moves per element, lg n = 16.61
n = 1000000: sorted, 19.00 buffer moves per element, lg n = 19.93
The I/O bound (stated, with the idea)
Theorem (Frigo et al. 1999; Brodal and Fagerberg 2002 for the lazy version). Under the tall-cache assumption , funnelsort sorts items with
which is optimal, without the algorithm knowing or .
Idea of the proof. Look at the funnels whose size is just right for the cache: those with about leaves where (more precisely, the recursion levels of the funnel structure whose total buffer space fits in words). Such a funnel, together with one block of each of its input buffers, fits in the cache; this needs , which holds because and tall cache gives . Once it is loaded, merging elements through it costs misses plus to reload input blocks, and an amortization over the buffer sizes (here the middle buffers are essential) shows that each element pays misses per such funnel level it passes. An element passes through funnels of that size (tall cache makes and the same up to a constant), giving the bound.
The tall-cache assumption is necessary
Brodal and Fagerberg (2003) proved that no cache-oblivious comparison-based sorting algorithm can match for all and without some tall-cache assumption: there is an inherent trade-off between how tall the cache must be and how close to optimal the algorithm is. The same is true for permuting. So the assumption for some is the price of obliviousness; funnelsort can be adapted to work under that weaker form.
| Algorithm | I/Os | Knows ? | Assumption |
|---|---|---|---|
| two-way merge sort | no | none | |
| multiway merge sort | yes | ||
| funnelsort, lazy funnelsort | no | (or ) | |
| cache-oblivious distribution sort (Frigo et al.) | no | tall cache |
Note: Funnelsort's constants and memory traffic are higher than those of a tuned cache-aware sort, so standard libraries do not use it. Experiments (Brodal, Fagerberg and Vinther, 2004) found lazy funnelsort competitive with good cache-aware quicksort and merge sort implementations once data exceeds main memory.
Test yourself
Into how many pieces does funnelsort split an input of items?
- 2
- , each of size
How much buffer space does a -funnel use in total?
What did Brodal and Fagerberg prove about the tall-cache assumption?
- It is never needed
- Some form of it is necessary for any cache-oblivious sorting algorithm to match the optimal cache-aware bound for all and
- It is only needed for matrix transposition
- It makes LRU optimal