0

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.

Linascts
  • 133
  • 6
  • 2
    Unless I'm missing something you want to order items by "property" of an array (which in you case is probably `array == null? 0 : array.Sum()`... If duplicate that I chose does not answer your question please [edit] post to clarify what exactly your requirements so regular Sort/OrderBy does not work for your case. – Alexei Levenkov Oct 05 '21 at 18:10

0 Answers0