C
C SUBROUTINE 'INDXRV'
C ===================
C
C INDEX A VECTOR OF REAL NUMBERS IN ASCENDING ORDER OF MAGNITUDE
C THE SORT IS STABILISED TO PRESERVE THE ORDER OF EQUAL VALUES
C
C BASED ON HEAP SORT METHOD DESCRIBED IN 'Numerical Recipes in C'
C by W. Press, B. Flannery, S. Teukolsky and W. Vetterling. Cambridge
C Universiry Press, 1988
C
C Stabilisation added by J. Campbell
C
C J. W. Campbell, 1992
C
      SUBROUTINE INDXRV (RV, N, INDX)
C
C PARAMETERS
C
C          RV (I)   VECTOR OF 'N' REAL NUMBERS TO BE INDEXED
C           N (I)   NUMBER OF ELEMENTS IN 'RV'
C        INDX (O)   RETURNS INTEGER VECTOR OF INDICES
C
C SPECIFICATION STATEMENTS
C ------------------------
C
      REAL RV(*)
      INTEGER INDX(*)
C
C SORT REALS
C ----------
C
      DO 20 I = 1 , N
         INDX(I) = I
 20   CONTINUE
      L = N/2 + 1
      IR = N
 30   IF (L.GT.1) THEN
         L = L - 1
         IT = INDX(L)
         RTEMP = RV(IT)
      ELSE
         IT = INDX(IR)
         RTEMP = RV(IT)
         INDX(IR) = INDX(1)
         IR = IR - 1
         IF (IR.EQ.1) THEN
            INDX(1) = IT
            RETURN
         END IF
      END IF
      I = L
      J = 2*L
 40   IF (J.LE.IR) THEN
         IF (J.LT.IR) THEN
            IF (RV(INDX(J)).LT.RV(INDX(J+1))) THEN
               J = J + 1
            ELSE IF (RV(INDX(J)).EQ.RV(INDX(J+1)) .AND. INDX(J)
     &               .LT.INDX(J+1)) THEN
               J = J + 1
            END IF
         END IF
         IF (RTEMP.LT.RV(INDX(J))) THEN
            INDX(I) = INDX(J)
            I = J
            J = J + I
         ELSE IF (RTEMP.EQ.RV(INDX(J)) .AND. IT.LT.INDX(J)) THEN
            INDX(I) = INDX(J)
            I = J
            J = J + I
         ELSE
            J = IR + 1
         END IF
         GO TO 40
      END IF
      INDX(I) = IT
      GO TO 30
      END
