3d array traversal originating from center
<p>I'm trying to find a traversal order for a 3d array with uniform dimension <code>n</code>.The traversal order should hereby be sorted ascending by it's distance to the cube's center (order of cells with equal indices is arbitrary).
Example for a 2d-Array:</p>

<pre><code>7 4 8
3 0 1
6 2 5
</code></pre>

<p>Which basically is the distance in <a href="https://en.wikipedia.org/wiki/Taxicab_geometry" rel="nofollow noreferrer">Manhattan metric</a>:</p>

<pre><code>2 1 2
1 0 1
2 1 2
</code></pre>

<p>Traversal as relative coordinates with respect to the origin:</p>

<pre><code>[ 0, 0]
[ 1, 0]
[ 0,-1]
[-1, 0]
[ 0, 1]
[ 1,-1]
[-1,-1]
[-1, 1]
[ 1, 1]
</code></pre>

<p>I know of some ways to solve this, for instance precalculating all indices and sorting them according to their distance to the origin. However, since this algorithm is intended to perform on <strong>GPU</strong>, there are some restrictions:</p>

<ol>
<li><strong>No recursion</strong> (I'm aware of the possibility resolving recursion into
an iterative algorithm - maintaining a stack is however not a
suitable solution in my experience) </li>
<li><strong>No offline calculation</strong> (= calculation on the CPU and transferring the result to the GPU). The solution needs to be as flexible as
possible</li>
</ol>

<p>While searching for solutions I stumbled upon this question, which is exactly the problem I tend to solve, the accepted answer albeit envolves a tree structure, which does not fit the specified requirements: <a href="https://stackoverflow.com/questions/24107769/3d-array-traversal-in-different-order">3D Array Traversal in Different Order</a></p>

<p>I also thought of a way to create the indices using spherical coordinates, which unfortunately does not yield the correct order. What is an appropriate algorithm to generate the given traversal order for 3d-arrays?</p>

<p>Edit: <a href="https://stackoverflow.com/questions/37214057/3d-array-traversal-originating-from-center#comment62309835_37398736">Stormwind</a> provided an excellent alternative description for the given Problem: "[The problem] is actually about converting addressing from one space to another. Converting between a 1-dimensional and 2-dimensional is simple, like 1,2,3,... to (1,1),(1,2)(2,1)... But this is more like converting from an ascending 1-dimensional (or at least square) to an "ascending octahedron layered" space, when "ascending" means "innermost layer first" in addition to an existing (though arbitrary) incrementing order at each layer surface."</p>