4

so if I have an array of characters

char[] chars = new char[]{'f','a','d','e','c','b'};

and another array of integers that say what the sort order is:

int[] sortOrder = new int[]{5,1,4,5,3,2};

how could I sort the data in the chars array, using the values in the sortOrder array to determine the order? In the above example, the sorted array would look like

{'a','b','c','d','e','f'}

(the 'd' moved to position 4, the 'a' to position 1, etc. Where the 5 is repeated, the order doesn't matter.)

I know I could do it by creating a third array, but ideally I would like to do it using LinQ (the .Sort) method or something similar, because there may be duplicated values in the sortOrder array.

I guess effectively I want to sort the sortOrder array (easy using sortOrder.Sort()), but then get it to sort the chars array with the exact same changes, somehow?

1
  • It would help if you added example output. For the arrays you listed above, what should the sorted array of characters look like? Commented Jul 2, 2010 at 14:39

1 Answer 1

11

There is an overload of Array.Sort that does exactly that...

Array.Sort(sortOrder, chars);

(note that this actually sorts both arrays in parallel - i.e. it sorts the keys, and makes the same swaps to the target array)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.