Adsense

Saturday, March 21, 2015

SEARCH and SEARCH ALL in COBOL with examples

SEARCH is a serial search.It can be used for both sorted and unsorted data inside the table.The table needs to be defined with an index .When we use the search function, the function starts with the current setting of the index and it goes on until to the end of the table.The starting value of the index is left upto the choice of the programmer. We can set the value of the index value just before the search starts using the SET keyword.

IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.

DATA DIVISION.
WORKING-STORAGE SECTION.
   01 WS-TABLE.
          05 WS-TEST PIC X(1) OCCURS 10 TIMES INDEXED BY I.

   01 WS-SRCH-STRNG PIC A(1) VALUE 'R'.

PROCEDURE DIVISION.
   MOVE 'ABCDEFRJKL' TO WS-TABLE.
   SET I TO 1.
   SEARCH WS-TEST
     AT END DISPLAY   'R NOT FOUND IN TABLE'
     WHEN WS-TEST(I)=WS-SRCH
     DISPLAY    'WE FOUND YOU IN THE TABLE'
   END-SEARCH.  

STOP RUN.

This linear Search will iterate through the entire table until the search-string is found or the end of table is reached.
In this case, since our search string 'R' is there in the table, the SYSOUT will display 'WE Found.. '.

SEARCH ALL is a binary search and the table must be sorted .That is the the prerequisite to use search all. The outcome of SEARCH ALL is either a yes or a no. Hence we can not code multiple search conditions when using SEARCH ALL function.
Contrary to search function, there is no need to initialize the index .

Check the following code:

IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.

DATA DIVISION.
   WORKING-STORAGE SECTION.
   01 WS-TABLE.
      05 WS-BIN-SRCH OCCURS 10 TIMES ASCENDING KEY IS WS-NUM INDEXED BY I.
      10 WS-ROLL PIC 9(2).
      10 WS-DEP PIC A(3).

PROCEDURE DIVISION.
   MOVE '12ABC56DEF34GHI78JKL93MNO11PQR' TO WS-TABLE.
   SEARCH ALL WS-BIN-SRCH
     AT END DISPLAY 'BIN-SRCH NOT FOUND'
     WHEN WS-ROLL(I)=93
     DISPLAY 'BIN-SRCH FOUND '
     DISPLAY WS-ROLL(I)
     DISPLAY WS-DEP(I)

Just a point to note:  The table is searched in ASCENDING ORDER. If you see, the table is defined with ASCENDING key clause. In case we want, we can always define the table in DESCENDING KEY clause.

When to use SEARCH and SEARCH ALL Function:
· For a table with less than 50 entries, go for SEARCH (Sequential Search)
· For a table with more than 50 entries go for SEARCH ALL (Binary Search)