Skip to content

Instantly share code, notes, and snippets.

@quaat
Created September 11, 2013 19:00
Show Gist options
  • Save quaat/6528212 to your computer and use it in GitHub Desktop.
Save quaat/6528212 to your computer and use it in GitHub Desktop.
Generic binarySearch algorithm in Fortran 2003 (pure, recursive)
program binSearchTest
integer :: idx
real, allocatable :: v(:)
integer, allocatable :: v2(:)
interface binarySearch
procedure binarySearch_real
procedure binarySearch_int
end interface binarySearch
! Test code
allocate(v(100))
allocate(v2(100))
do idx = 1, size(v)
v(idx) = idx * 1.2
end do
do idx = 1,size(v2)
v2(idx) = idx*2
end do
idx = binarySearch(v, 42.1)
print *, idx, v(idx), v(idx+1)
idx = binarySearch(v2, 120)
print *, idx, v2(idx), v2(idx+1)
!
contains
pure recursive function binarySearch_real(vec, scal, min, max) result (idx)
! input parameters
real, intent(in) :: vec(:)
real, intent(in) :: scal
integer, optional, intent(in) :: min
integer, optional, intent(in) :: max
! result
integer :: idx
!locals
integer :: i
! logic
if(.not.present(min)) then
idx = binarySearch_real(vec,scal, 1, size(vec))
else
i = ishft(min+max, -1)
if(scal >= vec(i) .and. scal < vec(i+1)) then
idx = i
else if( scal < vec(i) ) then
idx = binarySearch_real(vec,scal, min, ishft(min+max, -1) - 1)
elseif(scal > vec(i)) then
idx = binarySearch_real(vec,scal, ishft(min+max, -1) + 1, max)
end if
end if
end function binarySearch_real
pure recursive function binarySearch_int(vec, scal, min, max) result (idx)
! input parameters
integer, intent(in) :: vec(:)
integer, intent(in) :: scal
integer, optional, intent(in) :: min
integer, optional, intent(in) :: max
! result
integer :: idx
!locals
integer :: i
! logic
if(.not.present(min)) then
idx = binarySearch_int(vec,scal, 1, size(vec))
else
i = ishft(min+max, -1)
if(scal >= vec(i) .and. scal < vec(i+1)) then
idx = i
else if( scal < vec(i) ) then
idx = binarySearch_int(vec,scal, min, ishft(min+max, -1) - 1)
elseif(scal > vec(i)) then
idx = binarySearch_int(vec,scal, ishft(min+max, -1) + 1, max)
end if
end if
end function binarySearch_int
end program binSearchTest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment