diff --git a/src/util/util_sort.f90 b/src/util/util_sort.f90 index c24f81341..ca6e2d0e2 100644 --- a/src/util/util_sort.f90 +++ b/src/util/util_sort.f90 @@ -74,8 +74,7 @@ module pure subroutine util_sort_dp(arr) do i = 2, n tmp = arr(i) j = i - 1 - do while (j >= 1) - if (arr(j) <= tmp) exit + do while ((j >= 1) .and. (arr(j) > tmp)) arr(j + 1) = arr(j) j = j - 1 end do @@ -109,11 +108,11 @@ module pure subroutine util_sort_index_dp(arr, ind) do i = 2, n itmp = ind(i) j = i - 1 - do while (j >= 1) - if (arr(ind(j)) <= arr(itmp)) exit + do while ((j >= 2) .and. (arr(ind(j)) > itmp)) ind(j + 1) = ind(j) j = j - 1 end do + if ((j == 1) .and. (arr(ind(1)) > itmp)) ind(2) = ind(1) ind(j + 1) = itmp end do @@ -138,8 +137,7 @@ module pure subroutine util_sort_i4b(arr) do i = 2, n tmp = arr(i) j = i - 1 - do while (j >= 1) - if (arr(j) <= tmp) exit + do while ((j >= 1) .and. (arr(j) > tmp)) arr(j + 1) = arr(j) j = j - 1 end do @@ -170,14 +168,21 @@ module pure subroutine util_sort_index_i4b(arr, ind) allocate(ind(n)) ind = [(i, i=1, n)] end if + + itmp = ind(2) + if (arr(ind(1)) > itmp) then + ind(2) = ind(1) + ind(1) = itmp + end if + do i = 2, n itmp = ind(i) j = i - 1 - do while (j >= 1) - if (arr(ind(j)) <= arr(itmp)) exit + do while ((j >= 2) .and. (arr(ind(j)) > itmp)) ind(j + 1) = ind(j) j = j - 1 end do + if ((j == 1) .and. (arr(ind(1)) > itmp)) ind(2) = ind(1) ind(j + 1) = itmp end do @@ -202,8 +207,7 @@ module pure subroutine util_sort_sp(arr) do i = 2, n tmp = arr(i) j = i - 1 - do while (j >= 1) - if (arr(j) <= tmp) exit + do while ((j >= 1) .and. (arr(j) > tmp)) arr(j + 1) = arr(j) j = j - 1 end do @@ -237,11 +241,11 @@ module pure subroutine util_sort_index_sp(arr, ind) do i = 2, n itmp = ind(i) j = i - 1 - do while (j >= 1) - if (arr(ind(j)) <= arr(itmp)) exit + do while ((j >= 2) .and. (arr(ind(j)) > itmp)) ind(j + 1) = ind(j) j = j - 1 end do + if ((j == 1) .and. (arr(ind(1)) > itmp)) ind(2) = ind(1) ind(j + 1) = itmp end do