Sorting in Fortran
Our first example demonstrates sorting for built-in types in Fortran. We’ll use the intrinsic sort function for this purpose.
program sorting
implicit none
! Declare variables
integer, dimension(3) :: ints
character(len=1), dimension(3) :: chars
logical :: is_sorted
! Initialize arrays
chars = ['c', 'a', 'b']
ints = [7, 2, 4]
! Sort characters
call sort(chars)
print *, "Strings: ", chars
! Sort integers
call sort(ints)
print *, "Ints: ", ints
! Check if sorted
is_sorted = is_array_sorted(ints)
print *, "Sorted: ", is_sorted
contains
function is_array_sorted(arr) result(sorted)
integer, dimension(:), intent(in) :: arr
logical :: sorted
integer :: i
sorted = .true.
do i = 1, size(arr) - 1
if (arr(i) > arr(i+1)) then
sorted = .false.
exit
end if
end do
end function is_array_sorted
end program sortingIn this Fortran program:
We declare two arrays:
charsfor characters andintsfor integers.We use the intrinsic
sortfunction to sort both arrays. This function is part of Fortran’s standard library and works for various types including characters and integers.We print the sorted arrays using the
print *statement.To check if an array is sorted, we implement a custom function
is_array_sorted. This function iterates through the array and checks if each element is less than or equal to the next one.We then use this function to check if the
intsarray is sorted after applying thesortfunction.
To run the program, save it in a file (e.g., sorting.f90) and compile it using a Fortran compiler:
$ gfortran sorting.f90 -o sorting
$ ./sorting
Strings: a b c
Ints: 2 4 7
Sorted: TThis example demonstrates how to sort arrays of built-in types in Fortran and how to check if an array is sorted. Note that Fortran’s intrinsic sort function provides an easy way to sort arrays, but for more complex sorting scenarios or custom types, you might need to implement your own sorting algorithms.