Coding Cobol: A bubblesort

How easy is it to do a Bubblesort in Cobol? Not that challenging. Below is a Cobol program which prompts the user for the name of a file containing real numbers, and sorts them. The first piece of code below sets up the environment, and the information for the input file. The filename given by the user will be stored in fname-inp.

identification division.
program-id. stats.

environment division.
input-output section.
file-control.
select input-file assign to dynamic fname-inp
       organization is line sequential.

data division.
file section.
fd input-file.
01 sample-input     pic x(80).

The next section is the working-storage, which includes a bunch of variables for calculations, the input-value used to store the data as it is read from file, and the array x, where the data is ultimately stored.

working-storage section.
77 n          pic 9999 value 0.
77 feof       pic A(1).
77 temp       pic s9(14)v9(4) usage is computational-3.
77 fname-inp  pic x(30).
77 i          pic 9999.
77 j          pic 9999.
77 jp1        pic 9999.
77 jp2        pic 9999.

01 array-area.
   02 x pic s9(14)v9(4) usage is computational-3
      occurs 1000 times.

01 input-value.
   02 in-x   pic s9(14)v9(4).
   02 filler pic x(62).

The first part of the actual workings of the program, prompts the user for the filename, and reads the data into the array x.

procedure division.
   display "Input filename? "
   accept fname-inp.
   open input input-file.

   perform input-loop until feof='Y'
   perform bubblesort.
   perform print-nums.
   perform finish.

input-loop.
   read input-file into input-value
      at end move 'Y' to feof
      not at end
         add 1 to n
         move in-x to x(n)
   end-read.

The final portion of code includes three “subprograms” to perform the Bubblesort, print the array, and finish the program. The bubblesort just uses a normal Bubblesort algorithm. The perform statements take the place of Bubblesort’s usual for loops.

bubblesort.
   perform varying i from 1 by 1 until i is greater than n
      compute jp1 = n - i
      perform varying j from 1 by 1 until j is greater than jp1
         compute jp2 = j + 1
         if (x(j) > x(jp2))
            move x(j) to temp
            move x(jp2) to x(j)
            move temp to x(jp2)
         end-if
      end-perform
   end-perform.

print-nums.
   move 1 to i.
   perform until i > n
      display i "->"x(i)
      add 1 to i
   end-perform.

finish.
   close input-file.
   stop run.

The only difference is that instead of writing x(j+1), a variable, jp2, has to hold the value of j+1. If an attempt is made to use x(j+1), a compiler error of the form “error: ‘x’ requires one subscript” will occur.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.