
PROGRAM Test_Selection_Sort

  INTERFACE
    SUBROUTINE Selection_Sort(Item)
      INTEGER :: Item(:)
    END SUBROUTINE Selection_Sort
   END INTERFACE

  INTEGER, DIMENSION(5) :: X = (/ 55, 33, 77, 11, 22 /)


  PRINT *, "Unsorted List: ",  X
  CALL Selection_Sort(X)
  PRINT *, "  Sorted List: ",  X


END PROGRAM Test_Selection_Sort


! Selection_Sort -------------------------------------------------------
! Subroutine to sort Item(1), ..., Item(N) into ascending order using
! the simple selection sort algorithm. Variables used are:
!   Item              : array of integers to be sorted
!   NumItems          : number of items
!   I                 : subscript
!   TempLoc           : stores location of minimum value
!   SmallestItem      : smallest item in current sublist
!   Location_Smallest : location of SmallestItem
!
! Accepts:  Array Item
! Returns:  Array Item (modified) with first NumItems elements in
!           ascending order
!-----------------------------------------------------------------------

SUBROUTINE Selection_Sort(Item)

  INTEGER :: Item(:), TempLoc(1)
  INTEGER :: NumItems, I, SmallestItem, Location_Smallest

  NumItems = SIZE(Item)

  DO I = 1, NumItems - 1

!   Find smallest item in sublist Item(I), ..., Item(NumItems)

    SmallestItem = MINVAL(Item(I:NumItems))
    TempLoc = MINLOC(Item(I:NumItems))
    Location_Smallest = (I - 1) + TempLoc(1)

!   Interchange smallest item with Item(I) at
!   beginning of sublist

    Item(Location_Smallest) = Item(I)
    Item(I) = SmallestItem
  END DO

END SUBROUTINE Selection_Sort