# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module quantile2_mod
implicit none
  contains
! Two quantile utilities. Changed since formally tested.
!
! value = value of bb(k) if bb(1...n) were sorted into increasing order.
  real function quantile( k, bb)
    real :: bb(:)
    integer i, k, n
    real, allocatable :: aa(:)
    n=size(bb)
    allocate(aa(n))
    aa=bb
    call quantinternal( k, n, aa)
    quantile = aa(k)
    deallocate(aa)
  end function
  subroutine quantinternal( k, n, a)
    integer k, n
    real a(n)
    integer i, j, low, hi
    real ak, aa
    logical :: found
    if ( k>n .or. k<1) then
      call erexit("quant: inputs not in range  1 <= k <= n ")
    end if
    low = 1
    hi = n
    do while ( low < hi)
      ak = a(k)
      i = low
      j = hi
      found=.false.
      do while (.not. found)
        if ( a(i) < ak) then
          i = i+1
        else
          do while ( a(j) > ak)
            j = j-1
          end do
          if ( i > j) then
            found=.true.
            exit
          end if
          aa = a(i)
          a(i) = a(j)
          a(j) = aa
          i = i+1
          j = j-1
          if ( i > j) then
            found=.true.
            exit
          end if
        end if
      end do
      if ( j < k) then
        low = i
      end if
      if ( k < i) then
        hi = j
      end if
    end do
  end subroutine
end module
