简体   繁体   English

基于另一个1D数组的3D数组的快速排序

[英]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. 我有一个包含值的3D数组,我想根据1D数组中列出的值对其进行排序。 For example, 例如,

The 3d array has the values of: 3d数组的值为:

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 each other), then the result I want in the 3D array is: 因此,如果我们认为3D数组与1D数组相关(行彼此相关),那么我想要的3D数组的结果是:

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++: 这是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 . 现在,您可以使用argsort计算2D数组argsort For your example, argsort would return 1 2 0 . 对于您的示例, argsort将返回1 2 0

If you are intending to use C#, you could go for a LINQ query with a "group row by expression " clause. 如果打算使用C#,则可以使用带有“按表达式分组 ”子句的LINQ查询。 Depending on the source data and context, this could even be the preferrable way to sort the data. 根据源数据和上下文,这甚至可能是对数据进行排序的首选方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM