Preface – This post is part of the ABAP Programs series.
Linear Search in ABAP is an important topic in terms of interview question. In general, ABAP provides keyword “SEARCH” for searching purpose and that is widely used everywhere. In this article, we will learn: What is a Linear Search and how to implement it in our ABAP programs.
Table of Contents
What is a Linear Search?
A Linear Search is a search method in which a particular value is searched from an array(in case of ABAP, Internal table) of values via a procedure in which the value is compared with each of the values. The program to make a linear search in ABAP is shown below in the image and program:
Linear Search Program in ABAP
DATA : wa_data type int4, ITAB_data type TABLE OF int4, lv_lines type int1, flag type int1 value 0, pos type int1. SELECTION-SCREEN BEGIN OF SCREEN 0100 . "Where we create a Screen 0100 SELECT-OPTIONS: s_data FOR wa_data. "Seclect-Option for multiple Input PARAMETERS: p_input type int4. SELECTION-SCREEN END OF SCREEN 0100. DATA: wa_sdata LIKE LINE OF s_data. START-OF-SELECTION. CALL SELECTION-SCREEN 0100. LOOP AT s_data INTO wa_sdata. APPEND wa_sdata-low TO ITAB_data. ENDLOOP. DESCRIBE TABLE ITAB_data LINES lv_lines." Here we get total number of record loop at ITAB_data into wa_data. IF ( wa_data = p_input ). Flag = 1. pos = sy-tabix. EXIT. ENDIF. ENDLOOP. IF ( Flag = 1 ). Write: 'Hurray! Found your input @ position', pos. ELSE. Write 'Sorry! Not Found'. ENDIF.
In the program above, initially we have defined data types: One internal tables [to store input array of data], one work area [To be used by the above mentioned internal tabls], one variable [to save current line/index], one variable [to store current position], one variable to be used as a flag.
We have then created a selection screen to take input and save it in an internal table. Then using DESCRIBE, we will get the total number of records in that internal table. Then we use a loop and compare all the data and keep comparing the required data from them and set a flag as 1, if data is found. And in last, print either “Found” with position of the data or “Not Found”.