Our example demonstrates custom sorting in Fortran. We’ll sort strings by their length and a custom structure by age.
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:
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.