Papers
Topics
Authors
Recent
2000 character limit reached

Hilbert Curve Reordering

Updated 4 January 2026
  • Hilbert curve reordering is a mapping technique that transforms one-dimensional data into multi-dimensional structures while preserving locality.
  • It employs a recursive subdivision process with Gray code logic to efficiently convert linear indices to coordinate pairs.
  • Its superior spatial clustering benefits applications in visualization, memory optimization, and spatial indexing compared to traditional orderings.

Hilbert curve reordering is a technique for mapping one-dimensional data sequences or multi-dimensional arrays into higher-dimensional structures along the Hilbert space-filling curve, with the principal goal of preserving locality. This locality-preserving property yields tangible advantages for data visualization, memory layout optimization, parallel processing, spatial indexing, and token reduction in transformer architectures. The canonical Hilbert curve is a continuous, surjective, fractal mapping that visits every point in a 2D grid (or higher-dimensional generalization) exactly once in a path that clusters adjacent indices tightly in Euclidean space, outperforming classical scan or Morton/Z-order traversals in spatial compactness and neighborhood preservation.

1. Formal Definition and Algorithms for Hilbert Curve Mapping

The order-nn Hilbert curve is formally a bijection Hn:{0,1,,4n1}{0,1,,2n1}2H_n: \{0,1,\dots,4^n-1\} \rightarrow \{0,1,\dots,2^n-1\}^2, mapping a 1D index dd to a 2D coordinate pair (x(d),y(d))(x(d),y(d)) such that each position on a 2n×2n2^n \times 2^n grid is visited exactly once. The recursive construction proceeds by quadrant subdivision, where each level kk splits the current square into four sub-quadrants and arranges rotated or reflected copies of the lower-order curve according to a fixed entry/exit order. The Hilbert curve generalizes to dd dimensions via hypercube subdivision, Gray code orientation management, and coordinate permutation (Estevez-Rams et al., 2015, Bos et al., 2015, Haverkort, 2012, Walker, 2023).

The bitwise algorithm for d(x,y)d\to(x,y) or d(x1,,xd)d\to(x_1,\ldots,x_d) is a stack-free, iterative procedure that peels off quadrant bits, rotates and reflects coordinates via Gray code computations, and accumulates position increments at each scale. The inverse mapping (x,y)d(x,y)\to d uses similar Gray code and rotation logic with reverse traversal. For example, in 2D,

1
2
3
4
5
6
7
8
9
10
11
void d2xy(int n, int d, int &x, int &y) {
    x = y = 0; int t = d;
    for(int s=1; s < (1<<n); s <<= 1) {
        int rx = (t/2) & 1;
        int ry = (t ^ rx) & 1;
        rot(s, x, y, rx, ry);
        x += s * rx;
        y += s * ry;
        t /= 4;
    }
}

Analogous iterative algorithms exist for higher dimensions using signed permutations and orientation flags. For arbitrary dd and bit-width kk, the complexity per mapping is O(dk)O(dk) (Bos et al., 2015, Jaffer, 2014, Haverkort, 2012).

2. Locality Guarantees and Quantitative Evaluation

The Hilbert curve achieves near-optimal locality preservation. The dilation factor Γ(i,j)=d22/d1\Gamma(i,j) = d_2^2/d_1, relating squared Euclidean separation in 2D to index difference in 1D, is analytically bounded: Γ(i,j)6\Gamma(i,j)\leq 6 for all pairs in order-nn curves (Estevez-Rams et al., 2015), which is close to optimal.

For well-folded/hyperorthogonal Hilbert curves in higher dimensions, the bounding-box volume ratio (BCR) for any contiguous subchain of the curve satisfies BCR4\text{BCR}\leq 4, independently of dd; this is asymptotically tight (Bos et al., 2015). By contrast, Morton ordering can experience unbounded dilation and poor block clustering.

Global descriptors derived from locality maps—such as mean, median, and entropy of index jumps between neighbors—confirm that nearly all Hilbert variants and their kernel generalizations maintain high-quality clustering: typically >90%>90\% of sites show below-average jumps, and the mean difference between index-neighbors is markedly lower than for raster or Morton orderings (Pérez-Demydenko et al., 2013, Pérez-Demydenko et al., 2013).

3. Practical Applications: Visualization, Memory Layout, and Indexing

Hilbert curve reordering directly supports a range of applications:

  • Visualization of 1D sequences: Laying out a flat vector Σ0..L1\Sigma_{0..L-1} as a 2D image using the Hilbert mapping reveals local structure and periodicities more sharply than raster or Morton scans. Fourier analysis of Hilbert plots identifies symmetries and repeats at multiple scales (Estevez-Rams et al., 2015).
  • Cache-friendly memory access: Streaming data along Hilbert order facilitates cache-coherent block reads and minimizes TLB/cache misses in matrix multiplication, Cholesky decomposition, k-means clustering, and similarity joins. Speedups up to 2–4×\times in data mining applications have been reported (Böhm, 2020, Araújo et al., 2021).
  • R-trees and spatial indexing: Sorting multi-dimensional point sets by Hilbert index produces tight leaf bounding boxes, reducing coverage and overlap in spatial trees, and improving range query performance (Bos et al., 2015, Haverkort, 2012).
  • Load balancing in HPC: For grid-based parallel simulations, partitioning domains via Hilbert indices results in balanced workloads with favorable surface-to-volume ratios and connectivity, scaling efficiently to billions of cells (Liu et al., 2017).

4. Comparison with Alternative Reordering Schemes

Hilbert reordering consistently outperforms row-major and Morton (Z-order) traversals in locality. Fourier spectra of Hilbert-reordered arrays exhibit enhanced clustering and point-group symmetry, while row/Morton scans can generate cross-shaped artifacts or block boundary discontinuities (Estevez-Rams et al., 2015, Böhm, 2020).

However, in scenarios where minimizing run-length encoding (RLE) within individual columns of database tables is paramount, Hilbert ordering is suboptimal. Column-permutation followed by lexicographic sort—especially with low-cardinality columns first—beats Hilbert by factors up to 2–3×\times; Hilbert sorting is both column-order–oblivious and non-recursive, failing to produce extended blocks of constant values in any axis (0909.1346). The Hilbert curve’s spatial-locality objective is distinct from RLE optimization.

5. Generalizations and Curve Families

Homogeneous Hilbert curves (HHCs) in 2D admit 12 distinct patterns (six proper, six improper via reversion), each defined by affine map sequences and possible subcurve reversals. The choice among these affects boundary conditions, average/max jump length, and symmetry. All HHCs share similar locality properties, but specialized variants (e.g., those with closed walks or specific entry/exit alignments) may better suit applications along given directions or with pipeline constraints (Pérez-Demydenko et al., 2013, Estevez-Rams et al., 2013).

Beyond standard HHC, arbitrary kernel curves (HHCK) can be constructed by replacing the base pattern. Locality, as measured by dilation and difference maps, remains comparable across HHCK curves and classical Hilbert; well-chosen kernels can modestly enhance uniformity of adjacency (Pérez-Demydenko et al., 2013). For dimension-dd, harmonious Hilbert curves guarantee extradimensional compatibility—projecting down to any d<dd'<d face yields the dd'-dimensional Hilbert order—whereas Morton/Z lack this property (Haverkort, 2012, Haverkort, 2017).

6. High-dimensional and Variant Implementations

Pandimensional recurrences enable Hilbert curve reordering in arbitrary dimensions and with arbitrary side-length s2s\geq2. These recurrences are built from serpentine Hamiltonian cells, alignment transforms, and Gray-code logic, supporting both forward (index\rightarrowcoordinate) and inverse mapping in O(dlogsN)O(d\log_s N) time per point (Jaffer, 2014). In 3D, Hilbert ordering divides regions into five subblocks, each traced with a tracked 3×3 orientation matrix, generalizing the quadrant process of 2D curves (Walker, 2023).

In practical settings, reordering proceeds by mapping coordinates to Hilbert indices (or vice versa) and applying permutation to memory arrays, mesh elements, or image patches. For highly unstructured data, Hilbert-based sorting remains linear in the number of points, or O(nlogn)O(n\log n) if a full sort is required (Araújo et al., 2021, Böhm, 2020).

7. Contemporary Extensions: Vision Transformers and Token Reduction

Recent advances in applying Hilbert curve reordering to vision transformers (ViTs) exploit the locality-preserving mapping to allow neighbor-aware token reduction. Techniques such as Neighbor-Aware Pruning (NAP) and Merging by Adjacent Token similarity (MAT) use Hilbert ordering of image patches to expose and aggregate local context during attention computation (Li et al., 28 Dec 2025). Compared to canonical raster order, Hilbert-reordering ensures that consecutive tokens in the attention stream correspond to spatially adjacent patches, preserving neighborhood information and improving the accuracy-efficiency trade-off.

Empirical evaluations show consistent gains: For DeiT-B/384, NAP reaches higher Top-1 accuracy at the same FLOPs compared to EViT. For DeiT-S/224, MAT matches previous merging schemes but maintains neighborhood structure. Hybrid pruning+merging achieves both throughput and accuracy improvements. These neighbor-aware reductions are computationally efficient, resolution-agnostic, and plug-in compatible with existing ViT architectures.

Summary Table: Hilbert Curve Reordering vs. Alternatives

Property Hilbert Curve Morton/Z-order Lexicographic + Cardinality
Locality (dilation) \leq6 (2D), 4 (high-d) Unbounded at block boundaries Block-level, axis-specific
Extradimensionality Yes (harmonious, HHC) No Axis-preferential
RLE minimization Poor Poor Optimal (after permutation)
FFT symmetry Strong Noisy/cross-shaped artifacts Axis-aligned artifacts
Computational cost O(dk)O(d\,k) per mapping O(dk)O(d\,k) (interleaving only) Sorting overhead

Hilbert curve reordering is a locality-preserving, flexible strategy for mapping, visualization, data layout, and parallelization. Its algorithmic properties, quantitative locality measures, and optimal bounding-box performance support a broad spectrum of scientific, engineering, and machine learning applications, though in some specialized indexing cases alternative orderings may be preferable.

Whiteboard

Topic to Video (Beta)

Follow Topic

Get notified by email when new papers are published related to Hilbert Curve Reordering.