Ono
Ono

Reputation: 1357

Merging two ascending arrays in CUDA with ascending order

I have two float arrays

a = {1, 0, 0, 22, 89, 100};
b = {2, 3, 5, 0,  77,  98};

Both are monotonically increasing; Both with same length; Both may/may not have 0s inside. What I am trying to get is the new array combing both arrays in ascending order but without 0s:

c = {1, 2, 3, 5, 22, 77, 89, 98, 100 };

I cannot figure out how to write in CUDA code, unless I do a serial for loop, which I am trying to avoid. Any suggestions? Thanks.

Upvotes: 1

Views: 743

Answers (1)

m.s.
m.s.

Reputation: 16344

As Robert pointed out, thrust provides the basic building blocks for your needs.

merge.cu

#include <iostream>
#include <thrust/remove.h>
#include <thrust/merge.h>
int main()
{
   float a[6] = {1, 0, 0, 22, 89, 100};
   float b[6] = {2, 3, 5, 0,  77,  98};
   float c[12];
   thrust::merge(a,a+6,b,b+6,c);
   float* newEnd = thrust::remove(c,c+12,0);
   thrust::copy(c,newEnd, std::ostream_iterator<float>(std::cout, " "));
}

Compile and run:

nvcc -arch sm_20 merge.cu && ./a.out

Output:

1 2 3 5 22 77 89 98 100

Upvotes: 3

Related Questions