Internal Sort in COBOL

Introduction

  • Sorting plays an important role in arranging the records in ascending or descending order.
  • It performs sequential processing.
  • It is an essential requirement in all business-oriented applications to sort or merge a data in two or more files.
  • In COBOL, two techniques are used for sorting file i.e External sort and internal sort.
  • SORT verb is used to sort a file.

Sort Verb

Following files are used in Sort verb:

1) Input file – This file is used to sort in ascending or descending order.

2) Work file – This file holds the records while sorting process is in progress. In the sorting process, the input file records are transferred to work file. This file is defined in the File-Section under SD entry.

3) Output file – This file is the final output of the sort verb. It acquires after sorting process.

Syntax

Following is the syntax of sorting a file:
SORT work-file ON ASCENDING KEY rec-key-1
       [ON DESCENDING KEY rec-key-1]
USING input-file GIVING output-file.

SORT performs following operations:
  • SORT opens work-file in I-O mode, input-file in INPUT mode and output-file in OUTPUT mode.
  • The records in the input file are transferred into the work file.
  • Using the rect-key, it sorts the SORT-FILE in ascending or descending order.
  • Sorted record are transferred from work-file to the output-file.
  • It closes the input-file & output-file and deletes the work-file.

Merge Verb

Merge verb is used to combine two or more identical sequenced files.

Syntax:
MERGE work-file ON ASCENDING KEY rec-key-1
          [ON DESCENDING KEY re-key2]
USING input-1, input-2 GIVING output-file.

In merge process, input files i.e input-1, input-2, work files, output files are used.

Merge performs following operations:
  • Merge opens work-file in the I-O mode, input-file in INPUT mode and output-file in OUTPUT mode.
  • The record in the input file are transferred to the work file.
  • Using the rect-key, it sorts the SORT-FILE in ascending or descending order.
  • Sorted records are transferred from work-file to output-file.
  • It closes the input-file & output-file and deletes the work-file.