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 sorting

In this Fortran program:

  1. We declare two arrays: chars for characters and ints for integers.

  2. We use the intrinsic sort function to sort both arrays. This function is part of Fortran’s standard library and works for various types including characters and integers.

  3. We print the sorted arrays using the print * statement.

  4. 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.

  5. We then use this function to check if the ints array is sorted after applying the sort function.

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:  T

This 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.