The Elk Code
sortidx.f90
Go to the documentation of this file.
1 
2 ! Copyright (C) 2002-2005 J. K. Dewhurst, S. Sharma and C. Ambrosch-Draxl.
3 ! This file is distributed under the terms of the GNU Lesser General Public
4 ! License. See the file COPYING for license details.
5 
6 !BOP
7 ! !ROUTINE: sortidx
8 ! !INTERFACE:
9 pure subroutine sortidx(n,x,idx)
10 ! !INPUT/OUTPUT PARAMETERS:
11 ! n : number of elements in array (in,integer)
12 ! x : real array (in,real(n))
13 ! idx : permutation index (out,integer(n))
14 ! !DESCRIPTION:
15 ! Finds the permutation index {\tt idx} which sorts the real array {\tt x}
16 ! into ascending order. No sorting of the array {\tt x} itself is performed.
17 ! Uses the heapsort algorithm.
18 !
19 ! !REVISION HISTORY:
20 ! Created October 2002 (JKD)
21 ! Included tolerance eps, April 2006 (JKD)
22 !EOP
23 !BOC
24 implicit none
25 ! arguments
26 integer, intent(in) :: n
27 real(8), intent(in) :: x(n)
28 integer, intent(out) :: idx(n)
29 ! local variables
30 integer i,j,k,l,m
31 ! tolerance for deciding if one number is smaller than another
32 real(8), parameter :: eps=1.d-10
33 if (n < 1) return
34 do i=1,n
35  idx(i)=i
36 end do
37 if (n == 1) return
38 l=n/2+1
39 k=n
40 do
41  if (l > 1) then
42  l=l-1
43  m=idx(l)
44  else
45  m=idx(k)
46  idx(k)=idx(1)
47  k=k-1
48  if (k == 1) then
49  idx(1)=m
50  return
51  end if
52  end if
53  i=l
54  j=l+l
55  do while (j <= k)
56  if (j < k) then
57  if (x(idx(j)) < x(idx(j+1))+eps) j=j+1
58  end if
59  if (x(m) < x(idx(j))+eps) then
60  idx(i)=idx(j)
61  i=j
62  j=j+j
63  else
64  j=k+1
65  end if
66  end do
67  idx(i)=m
68 end do
69 end subroutine
70 !EOC
71 
pure subroutine sortidx(n, x, idx)
Definition: sortidx.f90:10