|
7.4 SORT and MERGE
If you wished to take a file of unordered records and produce a new file of these records sorted into ascending
or descending order of a field you would use SORT. The League table program
in the Sample code section uses this utility to generate a league table from updated records from a data file,
sorted principally by descending points.
Consider this segment of code from this program:
In addition to the FD for the TEAM-REC-IN (the main data file) there is also a WORK-FILE that the computer uses for sorting. Here it is assigned to SORTWK01, required for the Fujitsu COBOL compiler, but for MicroFocus you might code ASSIGN TO DISK or even ASSIGN TO "B:TEMPFILE". The WORK-FILE does not have a FD descriptor, but rather, has a sort descriptor SD.
The SORT-TABLE paragraph then sorts the data file TEAM-REC-IN as shown above. Note that the SORT verb is followed by WORK-FILE and that TEAM-REC-IN is refered to with USING... Since it is common for two teams to have the same number of points then, the DESCENDING KEY first attempts to sort by points (POINTS-KEY) but if these match then they are than sorted by goal difference (GD-KEY) and then by goals scored (GF-KEY). If these all match then the teams will be placed as the appear from the data file (for TEAM-REC-IN I placed them in alphabetical order). SORT-OUT is the destination of the sorted data where the new league table would appear. Note, a file that is to be sorted if already open, must be closed prior to sorting. THE SORT STATEMENT WILL AUTOMATICALLY OPEN THE UNSORTED FILE WHEN EXECUTED.        Merge To merge two sorted files into a single sorted file, the MERGE statement is used:
You can merge more than 2 files if you wish. An SD would be required as used with a SORT.
| ||||