Sorting an array related to another array

If y is always the tens value of x, y probably shouldn't exist - you should probably just calculate it's value directly off of x when needed.

In general, sorting parallel arrays is only possible (without hand rolling a sort algorithm) when the sort algorithm takes a custom "swap" function, which you can implement in terms of swapping elements in both arrays simultaneously. std::sort in C++ and qsort in C don't allow this.

Also in the general case, consider a single array where the element is a pair of items, rather than a parallel array for each item. This makes using "standard" algorithms easier.


Array.Sort has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys array:

int[] keys = { 1, 4, 3, 2, 5 };
string[] items = { "abc", "def", "ghi", "jkl", "mno" };
Array.Sort(keys, items);
foreach (int key in keys) {
    Console.WriteLine(key); // 1, 2, 3, 4, 5
}
foreach (string item in items) {
    Console.WriteLine(item); // abc, jkl, ghi, def, mno
}

So in your case, it sounds like you want:

Array.Sort(y,x); // or Sort(x,y); - it isn't  100% clear

How about?

var selectedArr = new int[] { 1, 3, 5, 7, 9 };
var unorderArr = new int[] { 9, 7, 5, 3, 1 };
var orderedArr = unorderArr.OrderBy(o => selectedArr.IndexOf(o));

Tags:

C#

Arrays