C
C SUBROUTINE 'INDXIV'
C ===================
C
C INDEX A VECTOR OF INTEGERS 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, 1990
C
      SUBROUTINE INDXIV (IV, N, INDX)
C
C PARAMETERS
C
C          IV (I)   VECTOR OF 'N' INTEGERS TO BE INDEXED
C           N (I)   NUMBER OF ELEMENTS IN 'IV'
C        INDX (O)   RETURNS INTEGER VECTOR OF INDICES
C
C SPECIFICATION STATEMENTS
C ------------------------
C
      INTEGER IV(*), INDX(*)
C
C SORT INTEGERS
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)
         ITEMP = IV(IT)
      ELSE
         IT = INDX(IR)
         ITEMP = IV(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 (IV(INDX(J)).LT.IV(INDX(J+1))) THEN
               J = J + 1
            ELSE IF (IV(INDX(J)).EQ.IV(INDX(J+1)) .AND. INDX(J)
     &               .LT.INDX(J+1)) THEN
               J = J + 1
            END IF
         END IF
         IF (ITEMP.LT.IV(INDX(J))) THEN
            INDX(I) = INDX(J)
            I = J
            J = J + I
         ELSE IF (ITEMP.EQ.IV(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
