Subroutine sort_students(students, num, comp_fn, which)
Use cs101
Implicit none
!****** declare arguments ***************************
Logical, External :: comp_fn
Integer, Intent(IN) :: num, which
TYPE (cs101student), Dimension(num), Intent(INOUT) :: students
!******** Local vars *********************************
Logical :: swapflag !flag that checks if any swaps are made
Integer :: i  !counter when looping
TYPE (cs101student) :: tmp  !for swapping
outer: DO
!initialize swapflag to fasle
 swapflag = .false.
! now go through the array seeing if any swap is needed.
 inner: Do i = 1, num - 1
    if (comp_fn(students(i+1), students(i), which)) Then
       ! swap the marks if i+1 is smaller than i
        tmp = students(i+1)
        students(i+1) = students(i)
        students(i) = tmp
       ! since we have swapped, we set swapflag to true
        swapflag = .true.
     end if
     End Do inner
! if no swaps were needed, then array is in sorted order. 
  if (.NOT. swapflag) EXIT
End Do outer
End Subroutine
