Sorting an array related to another array

2020-01-26 10:47发布

If I have two arrays, x and y where y is the value of the tens of every element in x. Now, I want to sort y. But, the order of y will be different of x's. So, I can't tell after sorting which element in y was related to, for instance, x[0]. I want a "double sorting" may be. Your help is infinitely appreciated!

标签: c# arrays
3条回答
家丑人穷心不美
2楼-- · 2020-01-26 10:58

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.

查看更多
Emotional °昔
3楼-- · 2020-01-26 11:08

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));
查看更多
看我几分像从前
4楼-- · 2020-01-26 11:15

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
查看更多
登录 后发表回答