# Generate this sequence more efficiently

Is there a more effecient way to generate the sequence shown below.

createOrder[n_] :=
Which[OddQ[n],
Join[Table[2 i - 1, {i, 1, (n + 1)/2}],Reverse@Table[2 i, {i, 1, (n + 1)/2}]],
EvenQ[n],
Join[Table[2 i - 1, {i, 1, n/2 + 1}],Reverse@Table[2 i, {i, 1, n/2}]]]

createOrder[#] & /@ Range[8] // MatrixForm


cg = Compile[{{a, _Integer, 1}, {b, _Integer, 1}, {i, _Integer}},
Join[a[[1 ;; Quotient[i + 1, 2]]], b[[-Quotient[i, 2] ;; -1]]],
CompilationTarget -> "WVM",
RuntimeAttributes -> {Listable},
Parallelization -> True
];
g[n_Integer] := cg[Range[1, n + 1, 2], Range[n + Mod[n, 2], 2, -2], Range[2, n + 1]];

• there's a little bug with g[n_?Integer], use g[n_Integer] or g[n_?IntegerQ] instead. Jan 18, 2019 at 10:01
• Good point, I added the pattern after posting... Jan 18, 2019 at 10:10
ClearAll[f]
f[n_Integer] := Join[Range[1, #, 2], Reverse[Range[2, #, 2]]] & /@ Range[2, n];
TeXForm @ MatrixForm @ f[8]


$$\left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \end{array} \right)$$

Also

ClearAll[f2, f3]
f2[n_Integer] := SortBy[Range@#, {EvenQ, -# (-1 )^Mod[#, 2] &}] & /@ Range[2, n]
f3[n_] := Ordering[Transpose[{-Mod[#, 2], -# (-1 )^Mod[#, 2]} &@Range[#]]] & /@ Range[2, n]

f[8] == f2[8] == f3[8]


True

   fGetList[n_]:= (Select[Range[#], OddQ]~Join~Reverse@Select[Range[#], EvenQ]) & /@Range[n] // Rest

fGetList[10] // MatrixForm // TeXForm


$$\left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \{1,3,5,7,9,8,6,4,2\} \\ \{1,3,5,7,9,10,8,6,4,2\} \\ \end{array} \right)$$

another version

fGetList2[n_?IntegerQ] :=
Flatten@MapAt[Reverse, GatherBy[Range[#], OddQ], 2] & /@ Range[2, n]

fGetList2[10] // MatrixForm // TeXForm


$$\left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \{1,3,5,7,9,8,6,4,2\} \\ \{1,3,5,7,9,10,8,6,4,2\} \\ \end{array} \right)$$