Bit*_*lue 6 c# sorting performance primitive
我需要一个float[]
待分类.我需要知道旧数组在新数组中的位置.这就是为什么我不能使用Array.Sort();
或其他什么.所以我想编写一个函数来为我排序数组,并记住每个值占用的索引:
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};
Run Code Online (Sandbox Code Playgroud)
阵列的大小约为500.我该如何处理?什么排序算法等
Array.Sort()
快我会接受它.
Mar*_*ell 12
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
Run Code Online (Sandbox Code Playgroud)
基本上,2参数版本Array.Sort
对两个数组应用相同的操作,在第一个数组上运行实际的排序比较.这通常用于反过来 - 通过所需的索引重新排列某些东西; 但这也有效.
您可以使用带有两个数组的Array.Sort()的重载,并根据它对第一个数组的排序方式对第二个数组进行排序:
float[] input = new [] { 1.5f, 2, 0, 0.4f, -1, 96, -56, 8, -45 };
int[] indices = Enumerable.Range(0, input.Length).ToArray();
Array.Sort(input, indices);
Run Code Online (Sandbox Code Playgroud)