# Modern Fortran sample code

**URL:** <https://fortran-lang.discourse.group/t/modern-fortran-sample-code/2019>\
**Category:** Help\
**Created:** [October 6, 2021, 9:24pm UTC](https://fortran-lang.discourse.group/t/modern-fortran-sample-code/2019 "2021-10-06T21:24:49Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Beliavsky](https://avatars.discourse-cdn.com/v4/letter/b/ba8739/32.png) [@Beliavsky](https://fortran-lang.discourse.group/u/Beliavsky)\
**Post date:** [October 6, 2021, 11:17pm UTC](https://fortran-lang.discourse.group/t/modern-fortran-sample-code/2019/2 "2021-10-06T23:17:01Z")

</div>

@Arjen [has shown](http://flibs.sourceforge.net/qsort_reals.f90) 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.

```auto
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:

```auto
   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](https://j3-fortran.org/doc/year/21/21-157r2.txt), the body of the function can be just one line:

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

```

---

_[View the full topic](https://fortran-lang.discourse.group/t/modern-fortran-sample-code/2019)._
