2011-05-11 88 views
0

我有一個包含數值的3D數組,我想根據1D數組中列出的值對它進行排序。 例如,基於另一個一維數組的3D數組快速排列

三維陣列具有的值:

1 2 3 
4 5 6 
7 8 9 

和1D陣列具有的值:

20 
11 
12 

因此,如果我們認爲3D陣列相關的1D陣列(行相互關聯),那麼我想在3D陣列中的結果是:

4 5 6 
7 8 9 
1 2 3 

我已經搜索了一個快速排序算法,但我找不到任何我想要的。

+2

您所談論的「3D陣列」實際上是一個2D陣列(兩維:行和列)。 – 2011-05-11 08:28:39

+0

你正在尋找的是一個真正的快速排序,沒有什麼特別的。您唯一需要做的就是以某種方式將排序的「鍵」與它們各自的「衛星」數據相關聯。 – ereOn 2011-05-11 08:33:30

+0

謝謝所有,其實它是3D,但我只是舉個例子來說明它:) – 2011-05-11 08:44:00

回答

1

你可以實現一個「參數快速排序」,它返回可以很容易地對數組進行排序的索引。這是在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); 
} 

現在你可以使用計算在argsort你的二維數組行的順序。舉例來說,argsort將返回1 2 0

0

如果你打算使用C#中,你可以「通過表達」條款去LINQ查詢了。 根據源數據和上下文,這甚至可能是排序數據的首選方式。

相關問題