且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#-对基元数组进行排序并跟踪其索引的最快方法

更新时间:2023-12-03 17:19:16

float[] input = new float[] { 1.5F, 2, 0, 0.4F, -1, 96, -56, 8, -45 };
int[] indices = new int[input.Length];
for (int i = 0; i < indices.Length; i++) indices[i] = i;
Array.Sort(input, indices);
// input and indices are now at the desired exit state

基本上,Array.Sort的2参数版本将相同的操作应用于两个数组,并在第一个数组上运行实际的 sort 比较.通常以另一种方式使用它-通过所需的索引重新排列某些内容;但这也可以.

Basically, the 2-argument version of Array.Sort applies the same operations to both arrays, running the actual sort comparisons on the first array. This is normally used the other way around - to rearrange something by the desired indices; but this works too.