Every database, search engine, or video game that stores two-dimensional data faces the same awkward question: how do you sort points on a flat surface into a single list? Latitude and longitude, pixel coordinates, map tiles — they live in 2D, but storage on disk or in memory is 1D.
The naive answer is row-major order: scan left to right, row by row. Simple — but disastrous for spatial queries. When you ask "give me all points within this rectangle," you end up jumping wildly back and forth across the list, because two cells that are neighbours on the grid might be hundreds of entries apart in the flat sequence.
The Z-order curve, invented independently by G. M. Morton in 1966 for IBM and later formalised in computer science, solves this with a beautiful bit trick. To compute the Z-index (also called the Morton code) of a point (x, y), you simply interleave the binary representations of x and y — alternating one bit from y, one from x, one from y, one from x, and so on. The resulting number traces a Z-shaped (or ⊓-shaped) path through the grid, and nearby points on the grid end up with Morton codes that are numerically close.
The algorithm runs in bit operations per coordinate, or in with modern CPU instructions like PDEP. And crucially, sorting points by their Morton code is exactly as easy as sorting any list of integers — standard algorithms apply unchanged.
Comments
Loading comments...