Dear fellow Natural developers
What is the best (fastest) way to sort an (dynamic) array in Natural? I use code like the following:
DEFINE DATA
*
PARAMETER
01 #ARRAY (A/1:*) DYNAMIC
*
LOCAL
01 #NUMBER-OF-ELEMENTS (I4)
01 #ARRAY-TEMP (A/1:*) DYNAMIC
01 #ELEMENT (A1000) /* DYNAMIC is not allowed with SORT!
01 #A (I4)
01 #T (I4)
*
END-DEFINE
*
********************************************************************************
DEFINE SUBROUTINE SORT-ARRAY
********************************************************************************
*
#NUMBER-OF-ELEMENTS := *OCC(#ARRAY)
IF #NUMBER-OF-ELEMENTS EQ 0
ESCAPE MODULE
END-IF
*
RESIZE ARRAY #ARRAY-TEMP TO (1:#NUMBER-OF-ELEMENTS)
#T := 0
*
FOR #A 1 #NUMBER-OF-ELEMENTS
#ELEMENT := #ARRAY(#A)
END-ALL
*
SORT BY #ELEMENT USING KEY
ADD 1 TO #T
#ARRAY-TEMP(#T) := #ELEMENT
END-SORT
*
RESET #ARRAY(*)
#ARRAY(*) := #ARRAY-TEMP(*)
*
END-SUBROUTINE
********************************************************************************
*
END
This works but I don’t know if it really is the best possible way. Especially when sorting a multi-dimensional array I need a temp field for every original field in the array and this is very error prone:
FOR #C 1 ARRAY.NUMBER-OF-ELEMENTS
#KEY-SORT := ARRAY.KEY
#VAR1-SORT := ARRAY.VAR1(#C)
#VAR2-SORT := ARRAY.VAR2(#C)
...
END-ALL
*
SORT BY #KEY-SORT USING
#VAR1-SORT
#VAR2-SORT
...
END-SORT
Is there a better way to sort an array?
Best regards,
Stefan