      SUBROUTINE INDEXX(N,ARR,INDX)
C
C     * THIS SUBROUTINE INDEXES AN ARRAY ARR(1:N), THAT IS, 
C     * IT OUTPUTS THE ARRAY INDX(1:N) SUCH THAT ARR(INDX(I)) IS 
C     * IN ASCENDING ORDER FOR I=1,2,...,N.
C     * THE INPUT VARIABLES N AND ARR ARE NOT CHANGED ON OUTPUT.
C
C     AUG 19/08 - SLAVA KHARIN
C     THE SUBROUTINE IS BORROWED FROM NUMERICAL RECIPES.
C     (C) COPR. 1986-92 NUMERICAL RECIPES SOFTWARE #=!E=#,)]UBCJ.
C
      INTEGER N,INDX(N),M,NSTACK
      REAL ARR(N)
      PARAMETER (M=7,NSTACK=50)
      INTEGER I,INDXT,IR,ITEMP,J,JSTACK,K,L,ISTACK(NSTACK)
      REAL A
      DO 11 J=1,N
        INDX(J)=J
 11   CONTINUE
      JSTACK=0
      L=1
      IR=N
 1    IF(IR-L.LT.M)THEN
        DO 13 J=L+1,IR
          INDXT=INDX(J)
          A=ARR(INDXT)
          DO 12 I=J-1,1,-1
            IF(ARR(INDX(I)).LE.A)GOTO 2
            INDX(I+1)=INDX(I)
 12       CONTINUE
          I=0
 2        INDX(I+1)=INDXT
 13     CONTINUE
        IF(JSTACK.EQ.0)RETURN
        IR=ISTACK(JSTACK)
        L=ISTACK(JSTACK-1)
        JSTACK=JSTACK-2
      ELSE
        K=(L+IR)/2
        ITEMP=INDX(K)
        INDX(K)=INDX(L+1)
        INDX(L+1)=ITEMP
        IF(ARR(INDX(L+1)).GT.ARR(INDX(IR)))THEN
          ITEMP=INDX(L+1)
          INDX(L+1)=INDX(IR)
          INDX(IR)=ITEMP
        ENDIF
        IF(ARR(INDX(L)).GT.ARR(INDX(IR)))THEN
          ITEMP=INDX(L)
          INDX(L)=INDX(IR)
          INDX(IR)=ITEMP
        ENDIF
        IF(ARR(INDX(L+1)).GT.ARR(INDX(L)))THEN
          ITEMP=INDX(L+1)
          INDX(L+1)=INDX(L)
          INDX(L)=ITEMP
        ENDIF
        I=L+1
        J=IR
        INDXT=INDX(L)
        A=ARR(INDXT)
 3      CONTINUE
        I=I+1
        IF(ARR(INDX(I)).LT.A)GOTO 3
 4      CONTINUE
        J=J-1
        IF(ARR(INDX(J)).GT.A)GOTO 4
        IF(J.LT.I)GOTO 5
        ITEMP=INDX(I)
        INDX(I)=INDX(J)
        INDX(J)=ITEMP
        GOTO 3
 5      INDX(L)=INDX(J)
        INDX(J)=INDXT
        JSTACK=JSTACK+2
        IF(JSTACK.GT.NSTACK)THEN
          WRITE(6,'(A)')'NSTACK TOO SMALL IN INDEXX'
          CALL                                     XIT('INDEXX',-1)
        ENDIF
        IF(IR-I+1.GE.J-L)THEN
          ISTACK(JSTACK)=IR
          ISTACK(JSTACK-1)=I
          IR=J-1
        ELSE
          ISTACK(JSTACK)=J-1
          ISTACK(JSTACK-1)=L
          L=I
        ENDIF
      ENDIF
      GOTO 1
      END
