Reputation: 13
So I've got a table of data in 2D array (first column is an ordinal number of the rows and the rest are data I'm working with). My question is basically how can I sort the rows based on the highest value in the last column (i.e. if the fourth row got the highest value in the last column it moves up to first row, and so on). random
in the code is just a method I made for generating floating numbers between x and y.
My code so far looks like this:
static float random(float min, float max)
{
System.Random random = new System.Random();
double val = (random.NextDouble() * (max - min) + min);
return (float)val;
}
static void Main(string[] args)
{
int temp = 0, i, j;
float[,] matrix;
matrix = new float[10, 5];
//generating ordinal number
for (i = 0; i < 10; i++)
{
matrix[i, 0] = ++temp;
}
//generating rest of the 2D array
for (i = 0; i < 10; i++)
{
for (j = 0; j < 5; j++)
{
matrix[i, 1] = random(60, 100);
matrix[i, 2] = random(50, 100);
matrix[i, 3] = random(40, 100);
matrix[i, 4] = (matrix[i, 1] + matrix[i, 2] + matrix[i, 3]) / 3;
}
}
for (i = 0; i < 10; i++)
{
for (j = 0; j < 5; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
}
Upvotes: 0
Views: 512
Reputation: 186668
I suggest using jagged array (array of array) float[][]
instead of 2d one float[,]
.
With jagged array you can sort in one simple line:
using System.Linq;
...
float[][] matrix = ...
// Column to compare
int column = 4; // or matrix[0].Length - 1; for the last olumn
Array.Sort(matrix, (left, right) => left[column].CompareTo(right[column])));
If you insist on having float[,]
you can copy it into jagged array, sort and then copy back:
float[,] matrix = ...
int column = 4;
float[][] temp = Enumerable
.Range(0, matrix.GetLength(0))
.Select(i => Enumerable
.Range(0, matrix.GetLength(1))
.Select(j => matrix[i, j])
.ToArray())
.ToArray();
Array.Sort(temp, (left, right) => left[column].CompareTo(right[column]));
for (int i = 0; i < temp.Length; ++i)
for (int j = 0; j < temp[i].Length; ++j)
matrix[i, j] = temp[i][j];
Upvotes: 1