C#-对基元数组进行排序并跟踪其索引的最快方法 [英] C# - Fastest Way To Sort Array Of Primitives And Track Their Indices
问题描述
我需要对float[]
进行排序.而且我需要知道旧索引在新数组中的位置.这就是为什么我不能使用Array.Sort();
之类的原因.因此,我想编写一个为我对数组进行排序的函数,并记住从哪个索引中获取每个值:
I need a float[]
to be sorted. And I need to know where the old indices are in new array. That's why I can't use Array.Sort();
or whatever. So I would like to write a function that sorts the array for me and remembers from what index it took each value:
float[] input = new float[] {1.5, 2, 0, 0.4, -1, 96, -56, 8, -45};
// sort
float[] output; // {-56, -45, -1, 0, 0.4, 1.5, 2, 8, 96};
int[] indices; // {6, 8, 4, 2, 3, 0, 1, 7, 5};
数组的大小大约为500.我应该如何处理呢?什么排序算法等
解决之后:它总是让我感到惊讶,C#如此强大.我什至不能独自完成这项任务.而且由于我已经听说
Array.Sort()
非常快,所以我接受它.
Size of arrays would be around 500. How should I approach this ? What sorting algorithm etc.
After solved: It always surprises me how powerful C# is. I didn't even though of it being able to do that task on it's own. And since I already heard that
Array.Sort()
is very fast I'll take it.
推荐答案
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.
这篇关于C#-对基元数组进行排序并跟踪其索引的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!