Is it possible to write a compile time recursive sort function in c++ using the selection algorithm?
I want to sort array x
from element istart
to element iend
in ascending order. Array x
has N
elements. The data in the input array x
is known only at runtime, hence the data can only be sorted at runtime. However, I want to generate the C++ code, i.e. all recursive function calls to sort_asc()
at compile time. Furthermore, I want to use this code in a CUDA device function. Since CUDA is a subset of C++ with a handful of extensions, I thought this was the right place to ask. Unfortunately, I don't think CUDA supports the constexpr
keyword, neither Boost nor STL.
I came up with the following code for sorting in ascending order.
// sort in ascending order.
template< int istart, int N, int iend, int iend_min_istart >
inline void sort_asc
(
float *x
)
{
int min_idx = istart;
float min_val = x[ min_idx ];
#pragma unroll
for( int i=istart+1; i<N; i++ ){
if( x[ i ] < min_val ){
min_idx = i;
min_val = x[ i ];
}
}
swap( x[ istart ], x[ min_idx ] );
sort_asc< istart+1, N, iend, iend-(istart+1) >( x );
}
where iend_min_istart = iend - istart
. If iend_min_istart < 0
then the recursion has finished, thus we can write the termination condition as:
// sort recursion termination condition.
template< int istart, int N, int iend >
inline void sort_asc< -1 >
(
float *x
)
{
// do nothing.
}
The swap function is defined as:
void d_swap
(
float &a,
float &b
)
{
float c = a;
a = b;
b = c;
}
Then I'd call the sort function as:
void main( int argc, char *argv[] )
{
float x[] = { 3, 4, 9, 2, 7 }; // 5 element array.
sort_asc< 0, 5, 2, 2-0 >( x ); // sort from the 1st till the 3th element.
float x_median = cost[ 2 ]; // the 3th element is the median
}
However, this code does not compile since c++ does not support partial template specialization for functions. Furthermore, I don't know how to write this in C++ meta programming. Is there any way to make this code work?