title: Sorting (small) arrays by key in CUDA
body: <p>I'm trying to write a function that takes a block of unsorted key/value pairs such as</p>
  
  <pre><code>&lt;7, 4&gt;
  &lt;2, 8&gt;
  &lt;3, 1&gt;
  &lt;2, 2&gt;
  &lt;1, 5&gt;
  &lt;7, 1&gt;
  &lt;3, 8&gt;
  &lt;7, 2&gt;
  </code></pre>
  
  <p>and sorts them by key while reducing the values of pairs with the same key:</p>
  
  <pre><code>&lt;1, 5&gt;
  &lt;2, 10&gt;
  &lt;3, 9&gt;
  &lt;7, 7&gt;
  </code></pre>
  
  <p>Currently, I'm using a <code>__device__</code> function like the one below which is essentially a bitonic sort that will combine values of the same key and set the old data to an infinitely large value (just using <code>99</code> for now) so that a subsequent bitonic sort will sift them to the bottom and the array cut by the value of <code>int *</code> removed.</p>
  
  <pre><code>__device__ void interBitonicSortReduce(int2 *sdata, int tid, int recordNum, int *removed) {
    int n = MIN(DEFAULT_DIMBLOCK, recordNum);
    for (int k = 2; k &lt;= n; k *= 2) {
      for (int j = k / 2; j &gt; 0; j /= 2) {
        int ixj = tid ^ j;
        if (ixj &gt; tid) {
          if (sdata[tid].x == sdata[ixj].x &amp;&amp; sdata[tid].x &lt; 99) {
            atomicAdd(&amp;sdata[tid].y, sdata[ixj].y);
            sdata[ixj].x = 99; 
            sdata[ixj].y = 99; 
            atomicAdd(removed, 1); 
          }   
          if ((tid &amp; k) == 0 &amp;&amp; sdata[tid].x &gt; sdata[ixj].x)
            swapData2(sdata[tid], sdata[ixj]);
          if ((tid &amp; k) != 0 &amp;&amp; sdata[tid].x &lt; sdata[ixj].x)
            swapData2(sdata[tid], sdata[ixj]);
          __syncthreads();
        }   
      }   
    }
  }
  </code></pre>
  
  <p>This works just fine for small sets of data but with larger sets (though still within the size of a single block) a single call just won't do it.</p>
  
  <p>Is it wise to try to combine the sorting and the reduction in the same function? Obviously the function would need to be called more than once but is it possible to determine exactly how many times it needs to be called to exhaust all the data based on its size?</p>
  
  <p>Or should I preform the reduction separately with something like this:</p>
  
  <pre><code>__device__ int interReduce(int2 *sdata, int tid) {
    int index = tid;
    while (sdata[index].x == sdata[tid].x) {
      index--;
      if (index &lt; 0)
        break;
    }
    if (index+1 != tid) {
      atomicAdd(&amp;sdata[index+1].y, sdata[tid].y);
      sdata[tid].x = 99;
      sdata[tid].y = 99;
      return 1;
    }
    return 0;
  }
  </code></pre>
  
  <p>I'm trying to come up with the most efficient solution, but my experience with CUDA and parallel algorithms is limited.</p>