[英]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.