1
int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};
int[] c = {30, 23, 90 ,110, 21, 34};

Now i want to sort a and use its index to sort b and c

For eg:

sorted a = {20,30,40,50,60,120};
sorted b should be ={ 11,63,85,37,29,12};
and sorted c should be = { 34,21,110,90,23,30};

How to do it in C#

6
  • 3
    Do you have to have three arrays? Typically a better approach here is to have a single array where each element is composed of the three values. That's generally cleaner as presumably the values are related to each other. Commented Oct 21, 2013 at 6:02
  • I tried to use sorting using keys and values .. like Array.Sort(a,c) and Array.Sort(a,b).. but I get unwanted results Commented Oct 21, 2013 at 6:03
  • I.e. Enumerable.Zip twice, OrderBy, than split again... Commented Oct 21, 2013 at 6:07
  • After executing Array.Sort(a, b), a and b will be out of sync, and thus you will mess up the relationship. Commented Oct 21, 2013 at 6:07
  • does your all array contains the same number of element? @user2546342 Commented Oct 21, 2013 at 6:16

5 Answers 5

2

One option:

int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};
int[] c = {30, 23, 90 ,110, 21, 34};

var ordered = a.Select((item, index) =>
                       Tuple.Create(item, b[index], c[index]))
               .OrderBy(tuple => tuple.Item1).ToArray();

a = ordered.Select(tuple => tuple.Item1).ToArray();
b = ordered.Select(tuple => tuple.Item2).ToArray();
c = ordered.Select(tuple => tuple.Item3).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

You could do it with a layer of indirection, like this:

  1. Put the values 0, 1, 2, ..., N-1 into an int array, named indices, say.
  2. Sort the array indices such that a[indices[i]] <= a[indices[i+1]] for all i. Your compare function will compare a[indices[Left]] with a[indices[Right]].
  3. Access elements in the other arrays using the indirection: a[indices[i]] and so on.

You could make new copies of a, b and c if you wish, using the order defined by indicies. But you also have the option of not modifying the original arrays.

This option of not modifying the original arrays is quite interesting. It allows you have have multiple simultaneous orderings active in tandem.

Comments

0

Got bored so I tried to minimise the creation of new objects and sorting.

static void Main(string[] args)
{
    int[] a = { 120, 60, 50, 40, 30, 20 };
    int[] b = { 12, 29, 37, 85, 63, 11 };
    int[] c = { 30, 23, 90, 110, 21, 34 };

    var indexes = Enumerable.Range(0, a.Length).OrderBy(i => a[i]).ToArray();

    var temp = new int[a.Length];
    foreach (var arr in new[] { a, b, c })
    {
        for (int i = 0; i < a.Length; i++) temp[i] = arr[indexes[i]];
        for (int i = 0; i < a.Length; i++) arr[i] = temp[i];
    }

    Console.WriteLine(String.Join(", ", a));
    Console.WriteLine(String.Join(", ", b));
    Console.WriteLine(String.Join(", ", c));
    Console.ReadLine();
}

Not the best it could be (I'm sure you can get rid of the temp array somehow) - but a different solution nonetheless. I'd support sticking with the LINQesque solutions until performance becomes an issue.

5 Comments

String.Join will not compute with int array. @NPSF3000
Your logic is correct but Could you please mention why Console.WriteLine(String.Join(", ", a)); giving me 2 compile time error. Error 1 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments Error 2 Argument '2': cannot convert from 'int[]' to 'string[]'
@Rezoan my guess is that you're using the .net 3.5 (or earlier) framework... or maybe mono? See msdn.microsoft.com/en-us/library/dd992421(v=vs.110).aspx for String.Join<T>
i am using version 3.5
@Rezoan String.Join<T> was added in 4.0.
0

You can use SortedList for this. SortedList sorts your items using a Key. Also it allows you to add new items to your collection.

SortedList Class: 
Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.

SortedList by MSDN

Comments

0

I suggest to use LINQ as Eli Arbel provided the answer. But here is an other solution for those who don't know LINQ.

class Program
    {
        public static int get_key(int key , int [,] keylist)
        {
            for (int i = 0; i <= keylist.GetUpperBound(0); ++i)
            {
                if (keylist[i, 0] == key)
                    return keylist[i, 1];
            }
            return -1;
        }
       public static int[] Sort_by_index(int [] arr , int [] key , int [,] index_list)
        {
            int[] _out = new int[arr.Length];

            for (int i = 0; i < key.Length; i++)
            {
                //Get key index
                int key_index = get_key(key[i], index_list);
                _out[i] = arr[key_index];

            }
            return _out;
        }
        static void Main(string[] args)
        {
            int[] a = { 120, 60, 50, 40, 30, 20 };
            int[] b = { 12, 29, 37, 85, 63, 11 };
            int[] c = { 30, 23, 90, 110, 21, 34 };
            int[,] a_index = { { 120, 0 }, { 60, 1 }, { 50, 2 }, { 40, 3 }, { 30, 4 }, { 20, 5 } };
            Array.Sort(a);
            b =Sort_by_index(b, a, a_index);
            c =Sort_by_index(c, a, a_index);
            Console.WriteLine("Result A");
            Console.WriteLine(string.Join(", ",a));
            Console.WriteLine("Result B");
            Console.WriteLine(string.Join(", ",b));
            Console.WriteLine("Result C");
            Console.WriteLine(string.Join(", ",c));
            Console.ReadKey(false);

        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.