Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort jagged array by row in C#?

I have 2D jagged array. And I want to sort it by any rows.

I've searched and found code for sorting by columns

private static void Sort<T>(T[][] data, int col) 
{ 
    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); 
}

Can I adapt it for sort by any rows ?

Any help is appreciated.

Sample of my jagged array (Added)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 10;
            int[][] capm = new int[3][];
            for (int i = 0; i <= 2; i++)
            {
                capm[i] = new int[n + 1];
            }
            Random rand = new Random();            
            for (int i = 1; i <= n; i++)
            {
                capm[1][i] = i;
            }

            for (int i = 1; i <= n; i++)
            {
                capm[2][i] = rand.Next(1, 6);
            }

            Sort(capm, 2);

            Console.ReadLine();
        }
            private static void Sort<T>(T[][] data, int col)    
            {  
                data = data.OrderBy(i => i[col]).ToArray();
            }
        }

    }

@Dani & @Martin I want my jagged array to sort by capm[2][].

like image 628
stereo Avatar asked Nov 17 '11 05:11

stereo


People also ask

How do you sort a 2D array in ascending order?

Make the 2D array into a separate simple (1D) array (STEP 1). Then use the Arrays. sort() method to sort the simple array (STEP 2). Then set each space of the 2D array to be the number of columns across (X-coordinate where the space will be changed) multiplied by the number of spaces per row in the 2D array.

Does C support jagged array?

The jagged arrays do exist in c++/c but the syntax is quite complex and you have to handle many things. There are two types of jagged arrays in c++. 1) STATIC JAGGED ARRAY(A 2d array in which the size will be a constant number and there will be different number of columns in each row).


1 Answers

The only way I can think of doing this is sorting by an array of indices:

private static void Sort<T>(T[][] data, int row) 
{
    int[] Indices = new int[data[0].Length];
    for(int i = 0; i < Indices.Length; i++)
        Indices[i] = i;

    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort(Indices, (x, y) => comparer.Compare(data[row][x], data[row][y]);

    for(int i = 0; i < data.Length; i++)
    {
        T[] OldRow = (T[])data[i].Clone();
        for(int j = 0; j < OldRow.Length; j++)
            data[i][j] = OldRow[i][Indices[j]];
    }
}
like image 58
Dani Avatar answered Sep 30 '22 03:09

Dani