Search code examples
ibm-midrangerpgleclrpg

How to retrieve MAX and MIN value of an integer array in RPGLE


In RPGLE (AS400) how to get the max and min value of an integer array.


Solution

  • While sorting the array would work, it's not particularly efficient for typical min/max usage. Sorting adds more overhead than a simple linear search and would really only be more effective if you wanted to get the values more than once on the sorted array and you don't ever need to add more unsorted data to that array.

    I'd recommend just implementing it yourself with a simple for loop:

    For Ix = 1 To %Elem(MyArray);
        If Array(Ix) > MyMax;
            MyMax = Array(Ix);
        EndIf;
        If Array(Ix) < MyMin;
            MyMin = Array(Ix);
        EndIf;
    EndFor;
    

    Depending on your usage scenarios, it could make sense to put that in a subprocedure or multiple subprocedures Max, Min, MinMax.