SEARCH statement

There are two types of SEARCH statements.

The first type, a serial search, starts with an element determined by the setting of the associated index. To search the entire table, the index must be set to one.

The second type is a binary search. It ignores the initial setting of the associated index and searches the entire table.

In both formats

The following data description is used in both examples of the SEARCH statement. The binary search requires that the KEY phrase be specified in the OCCURS clause, the serial search does not require this, but does allow it.

 working-storage section.
 01 states.
   03 state-abbr pic x(2) occurs 50 ascending key state-abbr indexed by i. 
 01 state-code pic x(2). 

The two coding examples are equivalent. They illustrate the difference between the serial and the binary search. In both examples, the user enters a two-character state abbreviation and the SEARCH statement is used to determine whether the entered abbreviation matches any of the valid abbreviations listed in the table. If the abbreviation is invalid, another one must be entered. A CONTINUE statement is coded at the location where you would process a valid state abbreviation, if additional processing beyond the validation were desired.

Serial Search

 enter-state. 
     accept state-code
     set i to 1
     search state-abbr
      at end display "invalid state code, please reenter" 
         go to enter-state
      when state-code = state-abbr (i)
         continue
     end-search
     stop run.

Binary Search

 enter-state. 
     accept state-code
     search all state-abbr
      at end display "invalid state code, please reenter" 
             go to enter-state
      when state-code = state-abbr (i)
         continue
     end-search
     stop run.

The differences in these two examples of the SEARCH statement are