简体   繁体   中英

Trying to arrange a 2D array in ascending order C#

I'm trying to arrange a 2D array in ascending order. This code runs for a 1D array but i'm struggling to implement it for 2D so that it places each row of the array in ascending order.

1D

    public static void Main(string[] args)
    {
        int[] sam = { 4, 7, 2, 0 };

        Array.Sort(sam);
        foreach (int value in sam)
        {
            Console.Write(value);
            Console.Write(' ');
        }
        Console.WriteLine();
    }

2D

public static void Main(string[] args)
        {
            int[] sam = { 4, 7, 2, 0 }, {4, 6, 2, 0};

            Array.Sort(sam);
            foreach (int value in sam)
            {
                Console.Write(value);
                Console.Write(' ');
            }
            Console.WriteLine();
        }

You can do something like this:

static void Main(string[] args) {
        int[][] sam = new int[2][];
        sam[0] = new int[] {4, 6, 2, 0};
        sam[1] = new int[] {4, 7, 2, 0};

        foreach(var array in sam)
        {
            Array.Sort(array);
            foreach(var item in array)
                Console.Write(item+" ");
            Console.WriteLine();
        }
}

Here, we are declaring a 2D array and then initializing each array one at a time. Then, we are looping through the sam array and then sorting each 1D array within it.

There are multiple solutions, one solution I'm thinking is using Array of Arrays ( Jagged Array ).

Let's say, if you have jagged array as defined below

    int[][]  numbers2 = new int[][] {
        new int[]{4,5,6}, 
        new int[]{1,2,3}, 
        new int[]{7,8,9}
        ...
    };

You can get sorted Jagged array using

int[][] sorted = numbers2.Select(x=> string.Join("-", x.ToArray()))
            .OrderBy(x=>x)
            .Select(x=> x.Split('-').Select(int.Parse).ToArray())       
            .ToArray(); 

Another option, let's your input is a 2d array you could do more or less same but output is sorted Jagged array.

int[][] sorted_array  = numbers.Cast<int>()     
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / (numbers.GetUpperBound(0) +1))
        .Select(x => string.Join("-", x.Select(v => v.Value)) )
        .OrderBy(x=>x)
        .Select(x=> x.Split('-').Select(int.Parse).ToArray())       
        .ToArray(); 

These are just my options, you will be the best to choose which is right to your solution.

Check this Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM