Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Fastest Way To Sort Array Of Primitives And Track Their Indices

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};

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.
like image 283
Bitterblue Avatar asked Jul 01 '13 08:07

Bitterblue


1 Answers

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

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.

like image 120
Marc Gravell Avatar answered Nov 14 '22 21:11

Marc Gravell