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!
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]);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With