Sorting in COBOL

Our program will demonstrate sorting in COBOL. We’ll look at sorting for different data types.

IDENTIFICATION DIVISION.
PROGRAM-ID. SORTING-EXAMPLE.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT WORK-FILE ASSIGN TO "WORK-FILE"
        ORGANIZATION IS SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD WORK-FILE.
01 WORK-RECORD.
   05 WORK-FIELD PIC X(10).

WORKING-STORAGE SECTION.
01 WS-STRING-ARRAY.
   05 WS-STRING OCCURS 3 TIMES PIC X(10).
01 WS-INT-ARRAY.
   05 WS-INT OCCURS 3 TIMES PIC 9(5).
01 WS-EOF PIC X VALUE 'N'.

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    PERFORM INITIALIZE-ARRAYS
    PERFORM SORT-STRINGS
    PERFORM SORT-INTS
    PERFORM CHECK-SORTED
    STOP RUN.

INITIALIZE-ARRAYS.
    MOVE 'c' TO WS-STRING(1)
    MOVE 'a' TO WS-STRING(2)
    MOVE 'b' TO WS-STRING(3)
    MOVE 7 TO WS-INT(1)
    MOVE 2 TO WS-INT(2)
    MOVE 4 TO WS-INT(3).

SORT-STRINGS.
    SORT WORK-FILE ON ASCENDING KEY WORK-FIELD
        USING WS-STRING-ARRAY
        GIVING WS-STRING-ARRAY
    DISPLAY 'Strings: ' WS-STRING-ARRAY.

SORT-INTS.
    SORT WORK-FILE ON ASCENDING KEY WORK-FIELD
        USING WS-INT-ARRAY
        GIVING WS-INT-ARRAY
    DISPLAY 'Ints:    ' WS-INT-ARRAY.

CHECK-SORTED.
    IF WS-INT(1) <= WS-INT(2) AND
       WS-INT(2) <= WS-INT(3)
        DISPLAY 'Sorted:  TRUE'
    ELSE
        DISPLAY 'Sorted:  FALSE'.

In COBOL, sorting is typically done using the SORT verb, which operates on files. We use a work file to perform the sorting operations.

For string sorting, we initialize an array of strings and use the SORT verb to sort them in ascending order. The result is then displayed.

Similarly, for integer sorting, we initialize an array of integers and sort them using the same method.

To check if a sequence is sorted, we manually compare the elements of the sorted integer array.

To run this program, you would compile it with a COBOL compiler and then execute the resulting program. The output would look something like this:

Strings: a  b  c     
Ints:    000020000400007
Sorted:  TRUE

Note that COBOL doesn’t have built-in slice or array sorting functions like some modern languages. Instead, it relies on file sorting mechanisms, which we’ve adapted for this example to sort our arrays.

COBOL’s strength in handling structured data and its sorting capabilities make it well-suited for processing large volumes of business data, which is why it’s still used in many enterprise systems today.