Subroutine to perform an insertion sort on a vector (single)
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
real, | intent(inout) | :: | x(:) | |||
integer, | intent(in) | :: | N |
SUBROUTINE Sort_sngl( x, N ) !! Subroutine to perform an insertion sort on a vector (single) INTEGER, INTENT( IN ) :: N REAL, INTENT( INOUT ) :: x(:) REAL :: xTemp IF ( N == 1 ) RETURN DO I = 2, N xTemp = x( I ) IF ( xTemp < x( 1 ) ) THEN x( 2 : I ) = x( 1 : I - 1 ) x( 1 ) = xTemp ! goes in the first position ELSE IF ( xTemp < x( I - 1 ) ) THEN ! Binary search for its place IRight = I - 1 ILeft = 1 DO WHILE ( IRight > ILeft + 1 ) IMiddle = ( ILeft + IRight ) / 2 IF ( xTemp < x( IMiddle ) ) THEN IRight = IMiddle ELSE ILeft = IMiddle ENDIF END DO ! Shift and insert x( IRight + 1 : I ) = x( IRight : I - 1 ) x( IRight ) = xTemp ENDIF END DO END SUBROUTINE Sort_sngl