COBOL by Example: Sort
Sorting files with built-in SORT verb for batch processing, defining Sort Description (SD) for temporary workspace, specifying ascending or descending sort keys, using USING and GIVING clauses for automatic file handling, and implementing INPUT/OUTPUT procedures for filtered sorting.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. SORT-DEMO.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO "input.dat".
SELECT SORT-FILE ASSIGN TO "sortwork".
SELECT OUT-FILE ASSIGN TO "sorted.dat".
DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-REC PIC X(20).
SD SORT-FILE.
01 SORT-REC.
05 S-ID PIC 9(5).
05 S-NAME PIC X(15).
FD OUT-FILE.
01 OUT-REC PIC X(20).
PROCEDURE DIVISION.
SORT SORT-FILE
ON ASCENDING KEY S-ID
USING IN-FILE
GIVING OUT-FILE.
DISPLAY "Sort Complete.".
STOP RUN.Explanation
The SORT verb is a powerful built-in feature that allows you to sort a file based on one or more keys. It handles opening, reading, sorting, and writing the data automatically, often much faster than an external bubble sort. This internal sort capability is one of COBOL's strengths in data processing.
You must define a "Sort Description" (SD) in the File Section. This acts as a temporary workspace for the sort operation. The system manages this space, which might be in memory or on a temporary disk area. The USING clause specifies the input file, and the GIVING clause specifies the output file.
For more complex scenarios, you can use INPUT PROCEDURE and OUTPUT PROCEDURE instead of USING/GIVING. This allows you to filter or modify records on the fly as they enter or leave the sorting process, effectively combining a sort step with a processing step.

