next up previous contents
Next: USE Renames Statement Up: Binary Cut Previous: Binary Cut

Solution

  MODULE binary_cut_module

   IMPLICIT NONE

  CONTAINS

   FUNCTION binary_cut(arr, i)
    INTEGER :: binary_cut, i, N
    INTEGER, DIMENSION(:) :: arr
    INTEGER :: low, high, halfway
     N = SIZE(arr)
     low = 1
     high = N
     DO
      PRINT*, low, high
      IF (low >= high) EXIT
       halfway = low + (high-low)/2
       IF (i <= arr(halfway)) THEN
         high = halfway
       ELSE
        low  = halfway+1
       END IF
     END DO
     binary_cut = low
   END FUNCTION

  END MODULE

  PROGRAM test_binary_cut
   USE binary_cut_module
   IMPLICIT NONE
   INTEGER, DIMENSION(12) :: arr1 = &  ! even number of elements
      (/1, 3, 5, 5, 10, 23, 23, 34, 36, 45, 56, 65/)
   INTEGER, DIMENSION(13) :: arr2 = &  ! odd number of elements
      (/1, 3, 5, 5, 10, 23, 23, 34, 36, 45, 56, 65, 76/)
   INTEGER :: index1,index2,index3,index4

    index1 = binary_cut(arr1, 23)
    PRINT*, ' index = ' , index1, ' correct = 6'
    index2 = binary_cut(arr1, 36)
    PRINT*, ' index = ' , index2, ' correct = 9'
    index3 = binary_cut(arr2, 23)
    PRINT*, ' index = ' , index3, ' correct = 6'
    index4 = binary_cut(arr1, 36)
    PRINT*, ' index = ' , index4, ' correct = 9'

! pathological cases
    index1 = binary_cut(arr1, 1)
    PRINT*, ' index = ' , index1, ' correct = 1'
    index2 = binary_cut(arr1, 65)
    PRINT*, ' index = ' , index2, ' correct = 12'
    index3 = binary_cut(arr2, 1)
    PRINT*, ' index = ' , index3, ' correct = 1'
    index4 = binary_cut(arr2, 76)
    PRINT*, ' index = ' , index4, ' correct = 13'

END PROGRAM


next up previous contents
Next: USE Renames Statement Up: Binary Cut Previous: Binary Cut

©University of Liverpool, 1997
Thu May 29 10:11:26 BST 1997
Not for commercial use.