AS400 – Sorting in Both Ways


The SORTA opcode has always been used by the RPGers to sort arrays. It’s simple and easy to use and runs faster than any of the APIs. However, you always had to hard-code whether the sort was ASCENDing or DESCENDing on the D-spec for the array.

For example, we had to do this:

D Sales s 9p 2 dim(12) ASCEND

/free
SORTA Sales;


If you wanted to be able to sort the data both ways in the same program (i.e., both ascending and descending), you had to do a bit of fooling around. For example, you could use a pointer like this:

D Sales s 9p 2 dim(12) ASCEND
D Sales2 s like(Sales)
D dim(%elem(Sales)) DESCEND
D based(p_Sales2)

/free
p_Sales2 = %addr(Sales);

if (want_ascending);
sorta Sales;
else;
sorta Sales2;
endif;

With 7.1, IBM added (A) and (D) operation extenders to the SORTA opcode. That means you can specify ascending or descending on the opcode rather than the array, which also means you can switch. For example:

D Sales s 9p 2 dim(12)

/free
if (want_ascending);
sorta(a) Sales;
else;
sorta(d) Sales2;
endif;

About the Author