如何对大型二维数组C

如何对大型二维数组C

本文介绍了如何对大型二维数组C#进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在第3列上对这个由三双组成的大型数组进行排序... MAG:

I need to sort this large array of three doubles on Column 3... MAG:

double[,] StarList = new double[1000000, 3];

访问就像:

StarList[x, y++] = RA;

StarList[x, y++] = DEC;

StarList[x, y] = MAG;

性能很重要.

就地很好,但不是必需的.

In-place would be nice, but not required.

如果更好,更快,我可以将双打转换为Int32.

I can convert the doubles to Int32 if its better and faster.

谢谢...

推荐答案

简单方法:多维数组不适合这样做.您最好考虑使用其他表示形式.例如,以下struct的一维数组将与您的布局完全相同:

The easy way:Multidimensional arrays are just not for that. You'd better consider alternative representation. For instance, the one dimensional array of the following struct would have exactly the same layout as yours:

struct StarInfo { public double RA, DEC, MAG; }

声明:

var StarList = new StarInfo[1000000];

访问权限:

StarList[x].RA = RA;
StarList[x].DEC = DEC;
StarList[x].MAG = MAG;

并且可以轻松地进行排序:

And can easily be sorted:

Array.Sort(StarList, (a, b) => a.MAG.CompareTo(b.MAG));

困难的方法::如果您仍然坚持使用多维数组,则可以执行以下操作.

The hard way: If you still insist on using multidimensional array, here is what you can do.

首先,使用间接排序:

var sortIndex = new int[StarList.GetLength(0)];
for (int i = 0; i < sortIndex.Length; i++)
    sortIndex[i] = i;
Array.Sort(sortIndex, (a, b) => StarList[a, 2].CompareTo(StarList[b, 2]));

然后

(A)存储sortIndex并在需要按顺序访问列表行时使用它,即代替StarList[x, c]使用StarList[sortIndex[x], c]

(A) store the sortIndex and use it when you need to access your list rows in order, i.e. instead of StarList[x, c] use StarList[sortIndex[x], c]

(B)使用sortIndex和众所周知的原位算法对列表重新排序:

(B) reorder your list using sortIndex and a well known in situ algorithm:

var temp = new double[3];
for (int i = 0; i < sortIndex.Length; i++)
{
    if (sortIndex[i] == i) continue;
    for (int c = 0; c < temp.Length; c++)
        temp[c] = StarList[i, c];
    int j = i;
    while (true)
    {
        int k = sortIndex[j];
        sortIndex[j] = j;
        if (k == i) break;
        for (int c = 0; c < temp.Length; c++)
            StarList[j, c] = StarList[k, c];
        j = k;
    }
    for (int c = 0; c < temp.Length; c++)
        StarList[j, c] = temp[c];
}

请注意,执行此操作后,sortIndex数组将被销毁,必须将其丢弃(即,不要存储或使用它)

Note that after doing this, the sortIndex array is destroyed and must be discarded (i.e. don't store or use it)

这篇关于如何对大型二维数组C#进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:15