If you have the code that uses some array(s) working cool.
If i needed to write this code, i would use an internal sort to order the output and reference modificaton to parse the input.
Each "sort record" would contain:
05 sort-rec-no pic 9(5) (unless you have more than 99k records)
05 sort-tag pic xx.
05 sort-lth pic 99
05 sort-data pic x( ) - however long the max data lth
I'd define a "record count" in ws and increment this each time a record was read.
As i parsed the input, i'd create and release a record to the sort for each "entry". On return from the sort, i'd control on the "record number" and build the output, inserting the 50 entry where appropriate in each output record.
For the sort, input/output procedure would be used - not using/giving.