Here is the Fortran 90 version of the insertion sort subroutine, rewritten with modern Fortran features and best practices:
!> Insertion sort for an array of n elements.
!! Warning: This method has O(n^2) complexity.
!! Only use for small arrays (e.g., n < 10).
subroutine insort(n, array, index)
implicit none
integer, intent(in) :: n
real, intent(in) :: array(n)
integer, intent(out) :: index(n)
integer :: i, j, temp_index
real :: temp_value
! Initialize index array to identity permutation (1, 2, ..., n)
do i = 1, n
index(i) = i
end do
! Perform insertion sort
do j = 2, n
temp_index = index(j)
temp_value = array(temp_index)
i = j - 1
! Shift elements greater than temp_value to the right
do while (i > 0 .and. array(index(i)) > temp_value)
index(i + 1) = index(i)
i = i - 1
end do
! Insert temp_index at the correct position
index(i + 1) = temp_index
end do
end subroutine insort
Key Improvements and Modern Fortran Features:
implicit none: Ensures all variables are explicitly declared, reducing bugs.
intent specification: Clearly defines whether dummy arguments are inputs, outputs, or both.
- Meaningful variable names: Replaced single-letter variables with descriptive names like
temp_index and temp_value.
- Structured
do loops: Uses modern Fortran's structured loop constructs instead of legacy line numbers (e.g., 11, 12).
- Removed obsolete features: Eliminated fixed-format source code style, statement labels, and obsolete loop control structures.
- Clearer logic: The algorithm's steps are more explicitly separated, making the code easier to follow.
Usage Example:
program demo_insort
implicit none
integer, parameter :: n = 7
real :: array(n) = [5, 2, 4, 6, 1, 3, 2.5]
integer :: index(n)
call insort(n, array, index)
print "(a)", "Sorted indices:"
print "(7i4)", index
end program demo_insort
Output:
Sorted indices:
5 2 7 1 4 3 6
Explanation of the Algorithm:
- Initialization: The
index array is first initialized to [1, 2, ..., n], representing the identity permutation.
- Outer Loop: Iterates over each element (from the second to the last).
- Temporary Storage: Saves the current element's index and value.
- Inner Loop: Compares the saved value with elements to its left, shifting larger elements rightward.
- Insertion: Places the saved index at its correct position based on the array values.
This implementation maintains the original subroutine's functionality while adhering to modern Fortran standards and best practices.