I have a 2d array and I want to sort it by row meaning that if the array is
3 2 2 3 2 2 3 3 3 3
3 3 2 2 2 2 3 3 2 2
3 2 2 3 2 2 3 3 3 2
2 2 2 2 2 2 2 2 2 2
3 2 2 2 2 2 3 2 2 2
2 2 2 2 2 2 2 2 2 2
3 3 2 3 2 2 3 3 2 3
3 3 2 2 2 2 3 3 3 3
3 2 2 3 2 2 3 3 2 3
3 3 2 3 2 2 3 3 3 3
I want to take the array
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
3 2 2 2 2 2 3 2 2 2
3 2 2 3 2 2 3 3 2 3
3 2 2 3 2 2 3 3 3 2
3 2 2 3 2 2 3 3 3 3
3 3 2 2 2 2 3 3 2 2
3 3 2 2 2 2 3 3 3 3
3 3 2 3 2 2 3 3 2 3
3 3 2 3 2 2 3 3 3 3
I checked some implementations of radix sort in pure CUDA, but they seem rather complicated. Is there any relatively easy way to do this with Thrust?
It's possible to do this in thrust. One possible approach would be to create a custom sort functor that traverses the rows that are given to it (let's say the rows are identified via indices passed to the functor), and then decides the ordering of those rows.
To implement this, we can create an index array, one index per row, that we will sort. We will sort this index array based on the given data array (using the custom sort functor that orders rows).
At the end, the only thing we have sorted is the index array, but it is now in the order needed to re-arrange the rows if desired.
Here's a fully worked example:
I'm pretty sure this would be significantly more efficient if the data could be delivered in transposed form, and rearrange the code to sort columns instead of rows (i.e. sort the index vector based on columns in the data array, rather than rows). This would be more efficient for the underlying data access that would be driven by the sort functor.
I've omitted the step that actually moves the rows to their new positions, but hopefully this should be straightforward. The general methodology is hinted at in the method to output the result, although it can be done with a single thrust call if desired.