How to sort two arrays/vectors in respect to values in one of the arrays, using CUDA/Thrust
This is a conceptual question in regards programming.
To summarize, I have two arrays/vectors and I need to sort one with the changes propagating in the other as well, so that if I sort arrayOne, for each swap in the sort - the same thing happens to arrayTwo. Now, I know that std::sort allows you to define a comparison function (for custom objects I assume) and I was thinking of defining one to swap arrayTwo at the same time.
So what I want is - to sort the two vectors based on values in one of the vectors, using CUDA.
This is where my uncertainty rises, essentially I want to use the Thrust library to do the sort. Does it support the definition of a custom comparison function? If so, I still haven't figured out how to propagate the change in the arrayTwo though (since it will be CUDA based).
I really don't have the time to implement a custom parallel quicksort on CUDA, as much as I should/want to.
The reason
Essentially I need to perform sorting and calculation on a bunch of arrays of variables versus a single array (think regression trees). Naturally, I need to do so as quickly as possible, CPU based sort is just not quick enough.
#UPDATE
I should emphasize, I have no problems sorting the two on the host, I'm looking for a solution that uses CUDA. Thanks.
#UPDATE 2
I think I actually got lucky and found the solution since I posted the question, turns out Thrust actually provides exactly what I'm looking for by default:
#include <thrust/sort.h>
...
const int N = 6;
int keys[N] = { 1, 4, 2, 8, 5, 7};
char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'};
thrust::sort_by_key(keys, keys + N, values);
// keys is now { 1, 2, 4, 5, 7, 8}
// values is now {'a', 'c', 'b', 'e', 'f', 'd'}
*taken from http开发者_开发问答://code.google.com/p/thrust/wiki/QuickStartGuide#Fancy_Iterators*
So, now all I have to do is get two thrust::device_vectors out of the two arrays (that I have to get out of the 2D array). Happy.
Create a vector of integer indexes, initialised to { 0, 1, 2, 3, etc }. Each integer represents one position in your vector. Sort your vector of indexes using a custom comparision function that uses the indexes to refer to vector1. When finished you can use the sorted indexes to reorder vector1 and vector2.
But I don't think you can do this reordering in place, so you going to have to copy from vector to vector anyway, so I think Kerrek's suggestion is good too.
精彩评论