!===============================================================================
!
! Copyright (C) 2010 Yoshifumi Nakamura
!
! This file is part of BQCD -- Berlin Quantum ChromoDynamics program
!
! BQCD is free software: you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation, either version 3 of the License, or
! (at your option) any later version.
!
! BQCD is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with BQCD.  If not, see <http://www.gnu.org/licenses/>.
!
!-------------------------------------------------------------------------------
# include "defs.h"

!  return sorted real(8) and index
!
!-------------------------------------------------------------------------------
subroutine sortd(a, idx, n)
  implicit none
  integer :: n, idx(n)
  real(8) :: a(n), atmp
  integer :: i,j

!#ifdef DEBUG2
!  do i=1,n
!     write(0,*)"sortd:",i,a(i)
!  enddo
!#endif

  idx=1
  do j=2, n
    atmp=a(j)
    do i=j-1,1,-1
      if (a(i)<=atmp) goto 10
        a(i+1)=  a(i)
      idx(i+1)=idx(i)
    end do
    i=0
10    a(i+1)=atmp
    idx(i+1)=j
  end do

!#ifdef DEBUG2
!  do i=1,n
!     write(0,*)"sortd:",idx(i),a(i)
!  enddo
!#endif


end
!===============================================================================
