Modern Fortran sample code

@Arjen has shown how to use recursion and the array functionality of Fortran (pack, array sections, vectorized comparisons) to write quicksort very concisely. Here is a lightly modified code of his, with a driver.

module qsort_mod
implicit none
contains
pure recursive function qsort(data) result(sorted)
real, intent(in) :: data(:)
real             :: sorted(size(data))
if (size(data) > 1) then
   sorted = [qsort(pack(data(2:),data(2:)<data(1))), data(1), &
             qsort(pack(data(2:),data(2:)>=data(1)))]
else
   sorted = data
end if
end function qsort
end module qsort_mod
!
program main
use qsort_mod, only: qsort
implicit none
real :: x(10)
call random_seed()
call random_number(x)
write (*,"(a10,*(1x,f0.3))") "initial",x
write (*,"(a10,*(1x,f0.3))") "sorted",qsort(x)
end program main

sample output:

   initial .869 .394 .228 .657 .793 .416 .494 .657 .851 .471
    sorted .228 .394 .416 .471 .494 .657 .657 .793 .851 .869

Edit: With the newly approved conditional expressions, the body of the function can be just one line:

sorted = (size(data) > 1 ? &
      sorted = [qsort(pack(data(2:),data(2:)<data(1))), data(1), &
                qsort(pack(data(2:),data(2:)>=data(1)))] : & 
      data )
11 Likes