COBOL Program to implement Binary
Search Concept.
PROGRAM:
IDENTIFICATION DIVISION.
PROGRAM-ID BINSER.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 ARRAY.
02 A1 PIC 9(4)V99 OCCURS 9 TIMES.
77 I PIC 9(3).
77 N PIC 9(3).
77 LOW PIC 9(3).
77 HIGH PIC 9(3).
77 MID PIC 9(3).
77 ELE PIC 9(4)V99.
PROCEDURE DIVISION.
MAIN-PARA.
DISPLAY " ENTER THE TOTAL
NUMBER OF ELEMENTS".
ACCEPT N.
DISPLAY " ".
DISPLAY " ENTER THE NUMBERS IN
ASCENDING ORDER ONLY".
DISPLAY " ENTER THE ARRAY
ELEMENTS:".
PERFORM ACC-PARA VARYING I FROM 1 BY
1 UNTIL I>N.
DISPLAY " ----------".
DISPLAY " ENTER THE NUMBER TO
BE SEARCHED".
ACCEPT ELE.
SEARCH-PARA.
COMPUTE LOW = 1.
COMPUTE HIGH = N.
PERFORM B1-PARA UNTIL LOW > HIGH.
DISPLAY " THE ELEMENT IS NOT
FOUND".
STOP RUN.
ACC-PARA.
ACCEPT A1 ( I ).
B1-PARA.
COMPUTE MID = ( LOW + HIGH ) / 2.
IF A1(MID) IS EQUAL TO ELE GO TO
DISP-PARA
ELSE
IF A1 ( MID ) < ELE
COMPUTE LOW = MID + 1
ELSE COMPUTE HIGH = MID - 1.
DISP-PARA.
DISPLAY " THE ELEMENT IS FOUND
AT POSITION", MID.
STOP RUN.
No comments:
Post a Comment