Sorting By Functions in Fortran
Our example demonstrates custom sorting in Fortran. We’ll sort strings by their length and a custom structure by age.
program sorting_by_functions
use, intrinsic :: iso_fortran_env, only: int32, real32
implicit none
type :: person
character(len=10) :: name
integer :: age
end type person
character(len=10), dimension(3) :: fruits
type(person), dimension(3) :: people
fruits = [character(len=10) :: "peach", "banana", "kiwi"]
call sort_by_length(fruits)
print *, "Sorted fruits: ", fruits
people(1) = person("Jax", 37)
people(2) = person("TJ", 25)
people(3) = person("Alex", 72)
call sort_by_age(people)
print *, "Sorted people: ", people
contains
subroutine sort_by_length(arr)
character(len=*), dimension(:), intent(inout) :: arr
integer :: i, j
character(len=len(arr)) :: temp
do i = 1, size(arr) - 1
do j = i + 1, size(arr)
if (len_trim(arr(i)) > len_trim(arr(j))) then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
end if
end do
end do
end subroutine sort_by_length
subroutine sort_by_age(arr)
type(person), dimension(:), intent(inout) :: arr
integer :: i, j
type(person) :: temp
do i = 1, size(arr) - 1
do j = i + 1, size(arr)
if (arr(i)%age > arr(j)%age) then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
end if
end do
end do
end subroutine sort_by_age
end program sorting_by_functions
In this Fortran program, we implement custom sorting for two different types:
- We sort an array of strings (
fruits
) by their length. - We sort an array of custom
person
structures by their age.
For the string sorting, we use a simple bubble sort algorithm that compares the trimmed length of each string. This is equivalent to the lenCmp
function in the original example.
For sorting the person
structures, we again use a bubble sort, this time comparing the age
field of each structure.
Fortran doesn’t have built-in generic sorting functions like slices.SortFunc
in Go, so we implement the sorting algorithms manually. This approach is more verbose but gives us full control over the sorting process.
To run this program, save it as sorting_by_functions.f90
and compile it with a Fortran compiler:
$ gfortran sorting_by_functions.f90 -o sorting_by_functions
$ ./sorting_by_functions
The output will show the sorted arrays of fruits and people.
Note that Fortran arrays are 1-indexed, unlike Go slices which are 0-indexed. Also, Fortran doesn’t have anonymous functions, so we define our sorting logic in separate subroutines.