开发者

Quicksort of 3D array based on another 1D array

I have a 3D array containg values and I want to sort it based on the values listed in 1D array. For example,

The 3d array has the values of:

1 2 3
4 5 6
7 8 9

and the 1D array has the values of:

20 
11
12

so if we considered that the 3D array is related the 1D array (rows are related to e开发者_Go百科ach other), then the result I want in the 3D array is:

4 5 6 
7 8 9
1 2 3

I have searched for a quicksort algorithm, but I couldn't find any for what I want.


You can implement a "argument quicksort" that returns the indices that would sort an array quite easily. Here is an implementation in C++:

#include <algorithm>

template <class IndexContainer, class DataContainer>
void arg_qsort(IndexContainer& indices,
               const DataContainer& data,
               int left,
               int right)
{
  int i = left;
  int j = right;
  int pivot = left + (right - left) / 2;

  while (i <= j)
  {
    while (data[indices[i]] < data[indices[pivot]])
      ++i;
    while (data[indices[j]] > data[indices[pivot]])
      --j;
    if (i <= j)
    {
      std::swap(indices[i], indices[j]);
      ++i;
      --j;
    }
  }

  if (left < j)
    arg_qsort(indices, data, left, j);
  if (i < right)
    arg_qsort(indices, data, i, right);
}


///
/// Compute the indices that would sort the given data.
///
template <class IndexContainer, class DataContainer>
void argsort(IndexContainer& indices, const DataContainer& data)
{
  int size = indices.size();
  if (size == 0)
    return;
  for (int i = 0; i < size; ++i)
  {
    indices[i] = i;
  }
  arg_qsort(indices, data, 0, size - 1);
}

Now you can compute the order of the rows in your 2D array using argsort. For your example, argsort would return 1 2 0.


If you are intending to use C#, you could go for a LINQ query with a "group row by expression" clause. Depending on the source data and context, this could even be the preferrable way to sort the data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜