Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort two arrays by same index?

Tags:

arrays

c#

sorting

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};

Array.Sort(b); // Now, b is -> b = {11, 12, 29, 37, 63, 85}

I want to sort a by b's index -> a = {20, 120, 60, 50, 30, 40}

If I have also string array c -> c = {"b", "u", "r", "s", "a", "1"}

I want to sort c by b's index -> c = {"1", "b", "u", "r", "a", "s"}

How can I do this? Thanks in advance, Regards.

like image 309
1teamsah Avatar asked Jun 13 '13 11:06

1teamsah


2 Answers

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 by b'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.

like image 150
jason Avatar answered Oct 14 '22 17:10

jason


// 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];
            }
        }
    }
like image 38
guest Avatar answered Oct 14 '22 16:10

guest