BudiBadu Logo
Samplebadu

COBOL by Example: Sort

COBOL 2002

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.

Code Breakdown

7
SELECT SORT-FILE. Defines the temporary work file used by the sort algorithm.
16
SD SORT-FILE. Sort Description. Unlike an FD, this describes a temporary stream, not a permanent file.
17
01 SORT-REC. The record layout for the sort file. The key fields must be defined here.
25
SORT SORT-FILE. The command to begin the sort operation.
26
ON ASCENDING KEY S-ID. Specifies the primary sort key. You can add more keys (e.g., THEN ON DESCENDING KEY S-NAME).
27
USING IN-FILE. The source file. It is opened, read, and closed automatically by the SORT verb.
28
GIVING OUT-FILE. The destination file. The sorted records are written here.