Table Look Up with Binary Search

Problem Statement

Given a sorted array and an arbitrary number, write a program using binary search to determine if that number is a member of the array. Your program should read in an array, then keeps asking for a number, does the search, and displays the location in the array where the data can be found.

Binary search goes as follows. Suppose we have n data items in ascending order. Let the first and the last one have subscripts Left and Right, respectively. Let the number to be searched for be Data. Now consider the middle element, Mid=(Left+Right)/2. If Data is equal to element Middle, then Middle is the location where Data can be found and we are done.

If Data is less than the data in location Middle, then all elements in the range of Middle and Right become irrelevant since they are all larger than Data, and can be eliminated from further consideration. To eliminate them, simply moving Right to the position of Middle-1 (i.e., Right=Middle-1) would be enough.

On the other hand, if Data is larger than the value in location Middle, then all elements in the range of Left and Middle become irrelevant and can be eliminated for further consideration. This can be achieved with moving Left to Middle+1 (i.e., Left=Middle+1).

Each time Left or Right change their positions, the number of elements to be considered is reduced to half of the original and hence the name of binary search. Eventually, either Data is found in some location, or Left and Right cross each other. The former case means that Data is found and the latter means Data is not a member of the given array.

Solution

! --------------------------------------------------------------------
! PROGRAM  TableLookUp
!    Given an array and a input value, this program can determine if
! the value if in the table.  If it is, the array location where the
! value is stored is returned.  Binary search is used.
! --------------------------------------------------------------------

PROGRAM  TableLookUp
   IMPLICIT  NONE
   INTEGER, PARAMETER              :: TableSize = 100
   INTEGER, DIMENSION(1:TableSize) :: Table
   INTEGER                         :: ActualSize
   INTEGER                         :: Key
   INTEGER                         :: Location
   INTEGER                         :: i
   INTEGER                         :: end_of_input

   READ(*,*)  ActualSize                ! read in the actual size and table
   READ(*,*)  (Table(i), i = 1, ActualSize)
   WRITE(*,*) "Input Table:"
   WRITE(*,*) (Table(i), i = 1, ActualSize)
   WRITE(*,*)
   DO                                   ! keep reading in a key value
      WRITE(*,*)  "A search key please --> "
      READ(*,*,IOSTAT=end_of_input)  Key
      IF (end_of_input < 0)  EXIT       ! EXIT of end-of-file reached
      Location = LookUp(Table, ActualSize, Key)   ! do a table look up
      IF (Location > 0) THEN            ! display the search result
         WRITE(*,*)  "Key value ", Key, " appears in location ", Location
      ELSE
         WRITE(*,*)  "Key value ", Key, " is not found"
      END IF
   END DO
   WRITE(*,*)
   WRITE(*,*) "Table lookup operation completes"

CONTAINS

! --------------------------------------------------------------------
! INTEGER FUNCTION  LookUp():
!    Given an array x() and a key value Data, this function determines
! if Data is a member of x().  If it is, the index where Data can be
! found is returned; otherwise, it returns 0.
! --------------------------------------------------------------------

   INTEGER FUNCTION  LookUp(x, Size, Data)
      IMPLICIT  NONE
      INTEGER, DIMENSION(1:), INTENT(IN) :: x
      INTEGER, INTENT(IN)                :: Size
      INTEGER, INTENT(IN)                :: Data
      INTEGER                            :: Left, Right, Mid

      LookUp = 0                        ! assume not found
      Left  = 1                         ! left end
      Right = Size                      ! right end
      DO                                ! loop until done
         IF (Left > Right)  EXIT        ! if left and right cross, exit
         Mid = (Left + Right) / 2       ! get the midpoint
         IF (Data == x(Mid)) THEN       ! is input = to the midpoint
            LookUp = Mid                ! Yes, record the position
            EXIT                        ! and exit
         ELSE IF (Data < x(Mid)) THEN   ! is Data < midpoint?
            Right = Mid - 1             ! YES, ignore the right half
         ELSE
            Left  = Mid + 1             ! otherwise, ignore the left half
         END IF
      END DO                            ! go back and try again
   END FUNCTION  LookUp

END PROGRAM  TableLookUp
Click here to download this program.

Program Input and Output

The output of the program is:
Input Table:
12,  29,  35,  40,  56,  68,  77,  84,  92,  96

A search key please -->
40
Key value 40 appears in location 4
A search key please -->
76
Key value 76 is not found
A search key please -->
92
Key value 92 appears in location 9
A search key please -->
100
Key value 100 is not found
A search key please -->
12
Key value 12 appears in location 1
A search key please -->
^D
Table lookup operation completes
Note that ^D is generated with Ctrl-D, which means ending the keyboard input and generating a end-of-file signal.

Discussion