Returns upper and lower indices of a 1-d sorted array using binary search in which a search value lies
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
real, | intent(in), | dimension(:) | :: | A | ||
real, | intent(in) | :: | x |
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