how can i get Array sort index?
-
Hi, all friends: i want to get a efficient function to sort array, and return a old array index . For example: double[] a=[5,4,1,3,2]; how can i get b is [1,2,3,4,5],and index array c is [2,4,3,1,0]? i want a efficent and quick method...
There is no built in method that will do that for you - the index to the previous array is what causes the problem - and you can't "retrospectively" find it because in the event of duplicates, you don;t know which value to use. What I would probably do is package the value you want to sort into a struct together with it's original index and sort that, using a comparator that looked only at the values. The resulting sorted info would include the original array index, and it would be pretty trivial to split them back up if you needed to.
public struct sortable
{
double value;
int index;
}Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
Hi, all friends: i want to get a efficient function to sort array, and return a old array index . For example: double[] a=[5,4,1,3,2]; how can i get b is [1,2,3,4,5],and index array c is [2,4,3,1,0]? i want a efficent and quick method...
-
-
Apart from typing it out manually? Just use a loop.
int[] index = new int[100];
for (int i = 0; i < index.Length; i++)
index[i] = i;inb4 `Enumerable.Range(0, 100).ToArray()` - oh sure, but that has the same loop, and also does a bunch of array allocations and copies. Sweeping a loop under the rug doesn't make it go away.
-
Apart from typing it out manually? Just use a loop.
int[] index = new int[100];
for (int i = 0; i < index.Length; i++)
index[i] = i;inb4 `Enumerable.Range(0, 100).ToArray()` - oh sure, but that has the same loop, and also does a bunch of array allocations and copies. Sweeping a loop under the rug doesn't make it go away.
-
Hi, all friends: i want to get a efficient function to sort array, and return a old array index . For example: double[] a=[5,4,1,3,2]; how can i get b is [1,2,3,4,5],and index array c is [2,4,3,1,0]? i want a efficent and quick method...
A little Linq, perhaps:
int[] iary = new[] { 5, 4, 1, 3, 2 };
var sorted = iary.OrderBy(itm1 => itm1).ToArray();
var unsortedIndexes = sorted.Select(itm2 => Array.IndexOf(iary, itm2, 0)).ToArray();Note that using 'OrderBy creates a copy of the Array.
>? sorted
{int[5]}
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5? unsortedIndexes
{int[5]}
[0]: 2
[1]: 4
[2]: 3
[3]: 1
[4]: 0? iary // after creating 'sorted using 'OrderBy
{int[5]}
[0]: 5
[1]: 4
[2]: 1
[3]: 3
[4]: 2«Tell me and I forget. Teach me and I remember. Involve me and I learn.» Benjamin Franklin