Internal Sort in COBOL Language
Sorting is a fundamental operation in data processing, and COBOL provides robust features to perform sorting efficiently. In this blo
g post, we’ll delve into internal sorting in COBOL, explain how it works, and provide an example to illustrate its usage.Understanding Internal Sorting in COBOL Language
Internal sorting in COBOL refers to the process of sorting data within the program’s memory (RAM) rather than using external sorting techniques. It is particularly useful when you need to sort a relatively small dataset that can fit into memory. COBOL offers the SORT
verb to perform internal sorting, making it an efficient and straightforward process.
The SORT
Verb in COBOL Language
The SORT
verb in COBOL allows you to sort data in memory. Here’s a simplified syntax for the SORT
verb:
SORT file-identifier
ON ASCENDING/DESCENDING key-1 key-2 ...
USING file-identifier
file-identifier
: Specifies the file or table to be sorted.ON ASCENDING/DESCENDING
: Indicates the sorting order for each key. You can sort keys in ascending or descending order.key-1, key-2, ...
: Specifies the key fields by which the data should be sorted.USING file-identifier
: Identifies the temporary working storage area where the sorted data will be stored.
Example: Internal Sorting
Let’s consider a simple example where we have a file with unsorted records of students’ names and their corresponding scores. We want to sort this data in ascending order of scores using COBOL’s SORT
verb:
IDENTIFICATION DIVISION.
PROGRAM-ID. InternalSortingExample.
DATA DIVISION.
FILE SECTION.
FD Student-File
RECORDING MODE IS F
BLOCK CONTAINS 0 RECORDS
DATA RECORD IS Student-Record.
01 Student-Record.
02 Student-Name PIC X(30).
02 Student-Score PIC 9(3).
WORKING-STORAGE SECTION.
01 Temp-Record.
02 Temp-Name PIC X(30).
02 Temp-Score PIC 9(3).
PROCEDURE DIVISION.
OPEN INPUT Student-File
OPEN OUTPUT Student-File-Sorted
PERFORM UNTIL EOF
READ Student-File
AT END
SET EOF TO TRUE
NOT AT END
MOVE Student-Name TO Temp-Name
MOVE Student-Score TO Temp-Score
WRITE Temp-Record FROM Student-Record
END-READ
END-PERFORM
SORT Student-File-Sorted
ON ASCENDING Student-Score
USING Temp-Record
CLOSE Student-File
CLOSE Student-File-Sorted
STOP RUN.
In this example:
- We define two file identifiers:
Student-File
for reading the unsorted data andStudent-File-Sorted
for writing the sorted data. - We read each unsorted record, store it temporarily, and write it to the output file.
- Finally, we use the
SORT
verb to sort the data in ascending order of scores using theStudent-Score
field as the sorting key.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.