繁体   English   中英

如何对大型2D数组进行排序

[英]How can I sort a large 2d array C#

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

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

访问就像:

StarList[x, y++] = RA;

StarList[x, y++] = DEC;

StarList[x, y] = MAG;

性能很重要。

就地会很好,但不是必需的。

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

谢谢...

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

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

宣言:

var StarList = new StarInfo[1000000];

访问:

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

并且可以很容易地进行排序:

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

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

首先,使用间接排序:

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]

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

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数组将被销毁,并且必须丢弃(即,不要存储或使用它)

暂无
暂无

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

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