!     Reordering of the particles in the computational cell
!     Particles are being reordered by their z coordinate
!     starting from zmin.  This is not the most efficient way
!     to reorder, but we are doing this only once, and the
!     efficiency is not so important here.
!     MSE 6270, Leonid Zhigilei

      SUBROUTINE Reorder()
      INCLUDE 'common.h'
      M1=NAN-1
      M2=M1
      outer_loop: DO J=1,M1
        inner_loop: DO I=1,M2
          test = XD(3,i+1)-XD(3,i)
          If (test.LT.0.0d0) then
            Rf=XD(3,I+1)
            XD(3,I+1)=XD(3,I)
            XD(3,I)=Rf

            Rf=XD(2,I+1)
            XD(2,I+1)=XD(2,I)
            XD(2,I)=Rf

            Rf=XD(1,I+1)
            XD(1,I+1)=XD(1,I)
            XD(1,I)=Rf

            Rf=POT(I+1)
            POT(I+1)=POT(I)
            POT(I)=Rf

            Nf=KHIST(I+1)
            KHIST(I+1)=KHIST(I)
            KHIST(I)=Nf

            Nf=KRIGID(I+1)
            KRIGID(I+1)=KRIGID(I)
            KRIGID(I)=Nf

            Nf=KTYPE(I+1)
            KTYPE(I+1)=KTYPE(I)
            KTYPE(I)=Nf
          END IF
        END DO inner_loop
        M2=M2-1
      END DO outer_loop
      RETURN
      END







