My task is to sum and sort the jagged array rows in ascending order, it got a little confusing, should I use some kind of sort algorithm or just swap the values?. For example:
Given Jagged Array: new[] { new[] { 2, -40, 55 }, new[] { 1 }, new[] { 1, 1 }, null, null }
Expected result: new[] { null, null, new[] { 1 }, new[] { 1, 1 }, new[] { 2, -40, 55 }
My code so far:
public static void OrderByAscendingBySum(this int[][] source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
int[] sum = new int[source.Length];
for (int i = 0; i < source.Length - 1; i++)
{
if (source[i] == null)
{
sum[i] = 0;
}
else
{
for (int j = 0; j < source[i].Length; j++)
{
sum[i] += source[i][j];
}
}
if (sum[i] > sum[i + 1])
{
int[] temp = source[i];
source[i] = source[i + 1];
source[i + 1] = temp;
}
}
}
What I am missing here? If you need more information please tell me I will update this, thank you.