getInterval Function

public function getInterval(A, x) result(indx)

Returns upper and lower indices of a 1-d sorted array using binary search in which a search value lies

Arguments

Type IntentOptional AttributesName
real, intent(in), dimension(:):: A
real, intent(in) :: x

Return Value integer, dimension(2)


Called by

proc~~getinterval~~CalledByGraph proc~getinterval getInterval program~demo1 demo1 program~demo1->proc~getinterval proc~getcm getCM proc~getcm->proc~getinterval proc~getcl getCL proc~getcl->proc~getinterval proc~getcd getCD proc~getcd->proc~getinterval

Contents

Source Code


Source Code

  function getInterval(A,x) result(indx)
    !! Returns upper and lower indices of a 1-d sorted array 
    !! using binary search in which a search value lies 
    real, intent(in), dimension(:) :: A 
    real, intent(in) :: x
    integer, dimension(2) :: indx  ! Left and right indices 
    integer :: n, i

    n = size(A,1)
    indx(1) = 1
    indx(2) = n

    ! Binary search algorithm
    do while ((indx(1) .ne. indx(2)) .and. (indx(2) .ne. (indx(1)+1)))
      i = floor((indx(1)+indx(2))*0.5)
      if (x < A(i)) then
        indx(2) = i
      elseif (x > A(i)) then
        indx(1) = i
      else
        indx(1) = i
        indx(2) = i
      endif
    enddo

    ! Check end cases
    if (abs(A(indx(1))-x) .le. epsilon(1.)) then
      indx(2) = indx(1)
    elseif (abs(A(indx(2))-x) .le. epsilon(1.)) then
      indx(1) = indx(2)
    endif
  end function getInterval