Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort 2d array rows in ascending order of their first elements in c#

Tags:

arrays

c#

sorting

I need to sort 2d array rows in ascending order of their first elements, like in example

{{5,7,6},{2,9,6},{4,8,1}} --> {{2,9,6},{4,8,1},{5,7,6}}

I can find max element in row, but i don't now how to sort the rows.

public double[] maxInRow(double[,] n) 
 { 
    double[] result = new double[n.GetLength(0)]; 
    for (int i = 0; i < n.GetLength(0); i++) 
    { 
        double max = 0;
        for (int j = 0; j < n.GetLength(1); j++) 
        { 
        if (max < n[i,j]) 
        { 
            max = n[i,j];
        } 
        } 
    result[i] = max; 
    } 
return result; 
}

Can you advice something?

Thanks in advance!

like image 540
Andriy Goroshko Avatar asked Dec 10 '22 19:12

Andriy Goroshko


2 Answers

Sadly with that sintax you are missing the power of linq wich is one of the best components of .Net framework you can try this instead

double[][] x = new double[2][];
x[0] = new double[] { 5, 2, 5 };
x[1] = new double[] { 6, 8, 3 };
x[2] = new double[] { 8, 3, 6 };

var sortedByFisrtVal =  x.OrderBy(y => y[0]);
var sortedBySecondVal = x.OrderBy(y => y[1]);

//trying to guess maybe this is better
var sorted =  x.OrderBy(y => y[0]).ThenBy(y => y[1]).ThenBy(y => y[2]);
like image 189
bto.rdz Avatar answered May 22 '23 09:05

bto.rdz


If performance is not critical then you can convert your 2D array into array of rows, sort them via OrderBy from linq providing the Max as the criteria and then convert the result back to 2D array:

        private static T[][] Convert<T>(T[,] source, int firstDim, int secondDim)
        {
            T[][] result = new T[firstDim][];
            for (int i = 0; i < firstDim; i++)
            {
                T[] temp = new T[secondDim];    
                for (int j = 0; j < secondDim; j++)
                {
                    temp[j] = source[i, j];
                }

                result[i] = temp;
            }

            return result;
        }

        private static T[,] ConvertBack<T>(T[][] source, int firstDim, int secondDim)
        {
            var result = new T[firstDim, secondDim];
            for (int i = 0; i < firstDim; i++)
            {
                for (int j = 0; j < secondDim; j++)
                {    
                    result[i, j] = source[i][j];
                }
            }

            return result;
        }

        // usage sample
        double[,] array = { { 5, 7, 6 }, { 2, 9, 6 }, { 4, 8, 1 } };
        int firstDim = array.GetUpperBound(0) + 1;
        int secondDim = array.GetUpperBound(1) + 1;
        double[][] jagged = Convert(array, firstDim, secondDim);

        // actual sort is done here!
        double[][] sorted = jagged.OrderByDescending(row => row.Max()).ToArray();

        double[,] result = ConvertBack(sorted, firstDim, secondDim);
like image 42
alex.b Avatar answered May 22 '23 08:05

alex.b