I have 2 arrays. I want to sort them by same index number. For example I have these:
int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};
Use Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items) that accepts two input arrays, one is the array of keys, the other is the array of items to sort using those keys. Here, for you, b
is your keys and a
is your items.
Thus:
Array.Sort(b, a);
will use the keys of b
to sort the items of a
.
I want to sort
c
byb
's index ->c = {"1", "b", "u", "r", "a", "s"}
Not clear exactly what you mean. At the same time as you sort a
using b
? If so, it's easy as we can still use the above. Zip a
and c
into a single array of Tuple<int, string>
.
var d = a.Zip(c, (x, y) => Tuple.Create(x, y)).ToArray();
Then:
Array.Sort(b, d);
as above. Then extract the pieces:
a = d.Select(z => z.Item1).ToArray();
c = d.Select(z => z.Item2).ToArray();
Alternatively, if you need to sort a lot of arrays using the same set of keys:
int[] indexes = Enumerable.Range(0, b.Length).ToArray();
Array.Sort(b, indexes);
Now you can use indexes
to sort all the arrays you need. For example:
a = indexes.Select(index => a[index]).ToArray();
c = indexes.Select(index => c[index]).ToArray();
etc. as needed.
Possibly some minor coding errors here. No compiler handy.
// a dirty and inefficient way of doing it,
// but should give you a heads up to get started
// you obviously dont want to modify array b, so making a copy
int[] c = Arrays.copyOf(b, b.length);
// now apply a sort on 'c' and apply the same operation on 'a' when modifying 'c'
// -> applying a bubble sort - > inefficient
for( int i = 0; i < c.length ; i ++) {
for( int j = 0 ; j < c.length - 1; j ++) {
if(c[j] > c [j+1]) {
c[j] = c[j] + c[j+1];
c[j+1] = c[j] - c[j+1];
c[j] = c[j] - c[j+1];
// apply the same to a
a[j] = a[j] + a[j+1];
a[j+1] = a[j] - a[j+1];
a[j] = a[j] - a[j+1];
}
}
}