2

I have a double 2D array:

a[0,0]=1.1      a[0,1]=0.1      a[0,2]=2.9      a[0,3]=1.6 
a[1,0]=-2.2     a[1,1]=-1.7     a[1,2]=0.3      a[1,3]=-0.4 
a[2,0]=2.0      a[2,1]=-0.1     a[2,2]=-1.8     a[2,3]=-3.1

1) I want to sort it in descending order AND save the 2 indexes (in order to know which array indexes has the absolute higher/lower values):

a[2,3]=-3.1
a[0,2]=2.9
a[1,0]=-2.2
a[2,0]=2.0
a[2,2]=-1.8
a[1,1]=-1.7
a[0,3]=1.6
a[0,0]=1.1
a[1,3]=-0.4
a[1,2]=0.3
a[0,1]=0.1
a[2,1]=-0.1

2) I also need a different sort: on the first index and save the 2nd index:

a[0,2]=2.9
a[0,3]=1.6
a[0,0]=1.1
a[0,1]=0.1

a[1,0]=-2.2
a[1,1]=-1.7
a[1,3]=-0.4
a[1,2]=0.3

a[2,3]=-3.1
a[2,0]=2.0
a[2,2]=-1.8
a[2,1]=-0.1

I don't know if I'm a moron of not :-) but I've unsuccessfully tried to understand the Microsoft "Array.Sort()" function variations to solve these problems.

Is it possible with "Array.Sort()" ?

I'm a beginner, some help will be greatly appreciated!

Thank you very much!

vindiou
  • 33
  • 3
  • 3
    Does this answer your question? [How do I sort a two-dimensional (rectangular) array in C#?](https://stackoverflow.com/questions/232395/how-do-i-sort-a-two-dimensional-rectangular-array-in-c) – panoskarajohn Dec 20 '19 at 12:14
  • I think this is what you want -> https://stackoverflow.com/a/232465/3902958, based on what you are asking. – panoskarajohn Dec 20 '19 at 12:17
  • I disagree, the examples you talk about don't correspond to my request – vindiou Dec 20 '19 at 15:10
  • Have you tried the example above and it is not working? I understand the example is different, but the end result is the same. Please try again or edit your question. – panoskarajohn Dec 20 '19 at 15:14
  • Please understand that I'm a beginner, I would have appreciated a little more help... – vindiou Dec 20 '19 at 15:29

1 Answers1

0

You can copy 2D array to 1D array. Then sort 1D array and recopy it to 2D array.

double[,] a = new double[3, 4];
a[0, 0] = 1.1; a[0, 1] = 0.1; a[0, 2] = 2.9; a[0, 3] = 1.6;
a[1, 0] = -2.2; a[1, 1] = -1.7; a[1, 2] = 0.3; a[1, 3] = -0.4;
a[2, 0] = 2.0; a[2, 1] = -0.1; a[2, 2] = -1.8; a[2, 3] = -3.1;
double[] oneD = new double[a.Length];
int t = 0;
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 4; j++)
    {
        oneD[t] = a[i, j];
        t++;
    }
}
Array.Sort(oneD);
oneD = oneD.Reverse().ToArray();
t = 0;
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 4; j++)
    {
        a[i, j] = oneD[t];
        t++;
    }
}
Murat Acarsoy
  • 294
  • 3
  • 10
  • Thanks but Compilation error (line 22, col 10): No overload for method 'Reverse' takes 0 arguments. – vindiou Dec 20 '19 at 15:13