subroutine test_valnth
use M_orderpack__valnth, only : valnth
implicit none
integer,allocatable :: iarr(:)
integer :: i
integer :: imiddle
call unit_check_start('valnth', '-library orderpack') ! start tests
! find Nth lowest value in an array without sorting entire array
iarr=[80,70,30,40,50,60,20,10]
! can return the same values as intrinsics minval() and maxval()
call unit_check('valnth',valnth(iarr,1).eq.minval(iarr),'like minval()')
call unit_check('valnth',valnth(iarr,size(iarr)).eq.maxval(iarr),'like maxval()')
! but more generally it can return the Nth lowest value.
call unit_check('valnth',valnth(iarr,8).eq.80,'Nth value')
! so a value at the middle would be
imiddle=(size(iarr)+1)/2
call unit_check('valnth',valnth(iarr,imiddle).eq.40,'find median')
! sort the hard way, one value at a time
call unit_check('valnth', all([(valnth(iarr,i),i=1,size(iarr))].eq.[10,20,30,40,50,60,70,80]),'sort hard way')
call unit_check_done('valnth',msg='test completed')
if(allocated(iarr))deallocate(iarr)
end subroutine test_valnth