Skip to content

Instantly share code, notes, and snippets.

@andersx
Last active January 31, 2020 13:16
Show Gist options
  • Save andersx/2562855b9257e704b1b7fe0c7efe9239 to your computer and use it in GitHub Desktop.
Save andersx/2562855b9257e704b1b7fe0c7efe9239 to your computer and use it in GitHub Desktop.
searchsorted and quicksort in f90
module searchtools
implicit none
contains
function searchsorted(all_values, sorted) result(cdf_idx)
implicit none
double precision, dimension(:), intent(in) :: all_values
double precision, dimension(:), intent(in) :: sorted
integer, allocatable, dimension(:) :: cdf_idx
double precision :: val
integer :: i, j, n, m
n = size(all_values)-1
m = size(sorted)
allocate(cdf_idx(n))
cdf_idx(:) = 0
do i = 1, n
val = all_values(i)
do j = 1, m
if (val < sorted(j)) then
cdf_idx(i) = j - 1
exit
endif
enddo
if (cdf_idx(i) .eq. 0) then
cdf_idx(i) = m
endif
enddo
end function searchsorted
recursive subroutine quicksort(a, first, last)
implicit none
double precision :: a(*), x, t
integer first, last
integer i, j
x = a( (first+last) / 2 )
i = first
j = last
do
do while (a(i) < x)
i=i+1
end do
do while (x < a(j))
j=j-1
end do
if (i >= j) exit
t = a(i); a(i) = a(j); a(j) = t
i=i+1
j=j-1
end do
if (first < i-1) call quicksort(a, first, i-1)
if (j+1 < last) call quicksort(a, j+1, last)
end subroutine quicksort
end module searchtools
program main
use searchtools!, only: searchsorted, qsort, group
implicit none
double precision, dimension(6) :: all_values
double precision, dimension(3) :: u_sorted
integer, allocatable, dimension(:) :: cdf_idx
integer :: n
all_values = (/0.2d0, 0.1d0, 0.3d0, 0.5d0, 0.6d0, 0.1d0/)
n = size(all_values)
write(*,*) all_values
call quicksort(all_values,1,6)
write(*,*) all_values
! all_values = (/0.1d0, 0.1d0, 0.2d0, 0.3d0, 0.5d0, 0.6d0/)
u_sorted = (/0.1d0, 0.2d0, 0.3d0/)
cdf_idx = searchsorted(all_values, u_sorted)
write(*,*) cdf_idx
end program main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment