Program binserachmain
 Implicit None
 Integer, Parameter :: maxsize = 100
 Integer, Dimension(maxsize) :: Nums
 Character(len=20) :: filename       ! Input data file name
 Integer :: nvals = 0                ! Number of data read
 Integer :: i, istat, temp                    ! Status: 0 for success
! Get the name of the file containing the input data.
Write (*,*) 'Enter the file name with the sorted data to be read: '
Read (*,'(A20)') filename
! Open input data file.  
Open (UNIT=9, FILE=filename, STATUS='OLD', IOSTAT=istat)
! Was the OPEN successful? 
fileopen: IF ( istat == 0 ) THEN         ! Open successful
   ! The file was opened successfully, so read the data from
   ! it, and store it in the linked list.
   input: DO
      READ (9, *, IOSTAT=istat) temp      ! Get value
      IF ( istat /= 0 ) EXIT              ! Exit on end of data 
      nvals = nvals + 1                   ! Bump count
      Nums(nvals) = temp                  ! put number in array
   End DO input
  End IF fileopen


  write (*,*) 'Which number you want to look for?-> '
  read (*,*) i
  if (i == 0) exit
	call binsearch(Nums,nvals,i,temp)
  write (*,*) i, 'Found at position: ', temp

 end do
End Program binsearchmain

Recursive Subroutine binsearch(Arr, size, val, ans)
  Integer, Intent(IN) :: size, val
  Integer, Intent(out) :: ans ! 0 if not found. else index.
  Integer, Dimension(size), Intent(IN) :: Arr
  Integer :: pos, tmp
write (*,*) "Bins called with array: ", (Arr(i),i=1,size), " size= ",size
  if (size == 1) then
     if (Arr(1) == val) then 
       ans = 1
    else
       ans = 0
    end if
  else
     pos = (1 + size) / 2  ! look at middle element
     write (*,*) 'Comparing: ',val, ' with: ', Arr(pos), &
          &  'at position: ', pos
     if (Arr(pos) == val) then 
          ans = pos
       else if (Arr(pos) > val) then
         if (pos > 1) then
            call binsearch(Arr(1:pos-1), pos-1, val, ans)
            write (*,*) 'Above ans = ', ans
         else
            ans = 0
         end if
       else
          call binsearch(Arr(pos+1:size),size-pos, val,ans)
            write (*,*) 'Below ans = ', ans
          if (ans > 0) ans = ans + pos !number is found
       end if
    end if
  end Subroutine binsearch
