EMPIRE DA  v1.9.1
Data assimilation codes using EMPIRE communication
 All Classes Files Functions Variables Pages
quicksort.f90
Go to the documentation of this file.
1 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2 !!! Time-stamp: <2014-09-22 15:48:46 pbrowne>
3 !This code was taken from http://rosettacode.org/wiki/Quicksort#Fortran
4 !and is distributed under GNU Free Documentation License 1.2.
5 !see http://www.gnu.org/licenses/fdl-1.2.html
9 recursive subroutine quicksort_d(a,na)
10 implicit none
11 ! DUMMY ARGUMENTS
12 integer, intent(in) :: nA
13 real(kind=kind(1.0D0)), dimension(nA), intent(inout) :: A
14 
15 ! LOCAL VARIABLES
16 integer :: left, right, mid
17 real(kind=kind(1.0D0)) :: pivot, temp
18 integer :: marker
19 
20  if (na > 1) then
21  ! insertion sort limit of 47 seems best for sorting 10 million
22  ! integers on Intel i7-980X CPU. Derived data types that use
23  ! more memory are optimized with smaller values - around 20 for a 16
24  ! -byte type.
25  if (na > 47) then
26  ! Do quicksort for large groups
27  ! Get median of 1st, mid, & last points for pivot (helps reduce
28  ! long execution time on some data sets, such as already
29  ! sorted data, over simple 1st point pivot)
30  mid = (na+1)/2
31  if (a(mid) >= a(1)) then
32  if (a(mid) <= a(na)) then
33  pivot = a(mid)
34  else if (a(na) > a(1)) then
35  pivot = a(na)
36  else
37  pivot = a(1)
38  end if
39  else if (a(1) <= a(na)) then
40  pivot = a(1)
41  else if (a(na) > a(mid)) then
42  pivot = a(na)
43  else
44  pivot = a(mid)
45  end if
46 
47  left = 0
48  right = na + 1
49 
50  do while (left < right)
51  right = right - 1
52  do while (a(right) > pivot)
53  right = right - 1
54  end do
55  left = left + 1
56  do while (a(left) < pivot)
57  left = left + 1
58  end do
59  if (left < right) then
60  temp = a(left)
61  a(left) = a(right)
62  a(right) = temp
63  end if
64  end do
65 
66  if (left == right) then
67  marker = left + 1
68  else
69  marker = left
70  end if
71 
72  call quicksort_d(a(:marker-1),marker-1)
73  call quicksort_d(a(marker:),na-marker+1)
74 
75  else
76  call insertionsort_d(a,na) ! Insertion sort for small groups is
77  ! faster than Quicksort
78  end if
79  end if
80 
81  end subroutine quicksort_d
82 
86 subroutine insertionsort_d(A,nA)
87 
88 ! DUMMY ARGUMENTS
89 integer, intent(in) :: nA
90 real(kind=kind(1.0D0)), dimension(nA), intent(in out) :: A
91 
92 ! LOCAL VARIABLES
93 real(kind=kind(1.0D0)) :: temp
94 integer :: i, j
95 
96  do i = 2, na
97  j = i - 1
98  temp = a(i)
99  do
100  if (j == 0) exit
101  if (a(j) <= temp) exit
102  a(j+1) = a(j)
103  j = j - 1
104  end do
105  a(j+1) = temp
106  end do
107 
108  end subroutine insertionsort_d
109 
subroutine insertionsort_d(A, nA)
subroutine to sort using the insertionsort algorithm
Definition: quicksort.f90:86
recursive subroutine quicksort_d(a, na)
subroutine to sort using the quicksort algorithm
Definition: quicksort.f90:9