An algorithm that is more efficient is described in John Skilling; Programming the Hilbert curve. AIP Conf. Proc. 21 April 2004; 707 (1): 381–387, which works in arbitrary dimensions by not relying on recursive geometry alignment.
This repository contains recursion-based implementation of Hilbert sorting algorithms for
Sorting, by intuition, gives an ordering of a set where the distance between neighboring elements is minimized. It is heavily used for DB indexing, visualization and a myriad of other purposes.
The distance may be measured in Hamming distance for bits, or Euclidean 2-norm for vectors.
Sometimes our data is multidimensional, like RGB colors {
One might use lexicographic sort, which compares the first non-identical component of tuples, but it
has many flaws. Take
Mapping from
Technically Hilbert Curves map the unit interval
$[0, 1]$ to the unit n-hypercube$U_n$ , but the hypercube could be offsetted and scaled to fit our data.
Neighboring tuples in the input space would also end up close to each other on the curve, preserving the spatial relationship between the input points.
Some properties of the Hilbert Curves allows us to implement a recursive algorithm:
Points on the Hilbert Curve converges to a definite point as iteration count increases.
This is not true for other curves in general, where the points would oscillate over iterations.
Every iteration
>
>
H_2 Overlay, First 3 Iterations
Images by Geoff Richards (Qef) - Own work, Public Domain
Taking the
Divide
The orientation of
$n$ -D Hilbert Curve is based off the Gray code sequence$G_n$ , generalizing the interpretation of the bits as mentioned above. ($G_n$ is a permutation of the bit code, which contains every vertex of$U_n$ )
This allows us to recursively divide points into quadrants and sort the quadrants instead, after
which we concatenate the results in
The recursion base is when only 1 or none vector is left, or if all vectors are identical. The input vectors would be returned. The recursion step aligns the vectors to fit the hypercube, recurse, and return de-aligned results.
The
The time complexity of the algorithm is
The space complexity of the algorithm is expected to be quite high, as recursion is heavily used.
Here the complexities are estimated assuming uniform distribution of points in
$U_n$ .
The algorithm could be used for fast approximations of the Travelling Salesman Problem. See Benchmark and Visualization.
An interactive demo is available at Hilbert Sort. It includes:
Notice it would roughly approximate a Hilbert Curve.
The result would be more gradient than the original.