C# How to sort a jagged array by index

107 Views Asked by At

I want to sort a jagged array by following condition:

if array[i][0] != array[j][0], compare by array[i][0] - array[j][0]
if array[i][0] != array[j][0], compare by i - j
i, j is index of array 

Here is an example:

int[][] array = new int[3][]
{
    new int[2] {1, 2},
    new int[2] {0, 1},
    new int[2] {1, 1}
};

sorted result

[[0, 1], [1, 2], [1, 1]]

i try to use IComparer but don't know how to implement or any other method to solve this problem.

Thanks

=====================================================================

Problem solved but got different result between Array.Sort() and Linq.

public void TestSort()
{
    int[][] array = new int[6][]
    {
        new int[4]{2,6,9,4},
        new int[4]{4,8,7,5},
        new int[4]{4,6,7,6},
        new int[4]{2,3,3,7},
        new int[4]{9,3,6,8},
        new int[4]{2,8,8,4}
    };

    // Use Array.Sort()
    JaggedArrayComparer cp = new JaggedArrayComparer();
    cp.array = array;
    Array.Sort(array, cp);
    Console.WriteLine("Sort by Array.Sort() =================");
    foreach (var e in array)
    {
        Console.WriteLine($"{e[0]} {e[1]} {e[2]} {e[3]}");
    }

    // Use Linq
    // array = array.OrderBy(a => a[0]).ThenBy(a => Array.IndexOf(array, a)).ToArray();
    // Console.WriteLine("Sort by Linq =================");
    // foreach (var e in array)
    // {
    //     Console.WriteLine($"{e[0]} {e[1]} {e[2]} {e[3]}");
    // }
}

class JaggedArrayComparer : IComparer
{
    public int[][] array;
    public int Compare(object x, object y)
    {
        int[] xArray = (int[])x;
        int[] yArray = (int[])y;

        if (xArray[0] != yArray[0])
        {
            return xArray[0] - yArray[0];
        }
        else
        {
            return Array.IndexOf(array, xArray) - Array.IndexOf(array, yArray);
        }
    }
}

Output:

enter image description here

enter image description here

Expect output is same as Linq Output. What is the reason

1

There are 1 best solutions below

3
Dor Lugasi-Gal On BEST ANSWER

I would use the Sort method and provide it with a comparer function as you like

something like this

Comparison<int[]> MyCoolComparison(List<int[]> intsList)
{
    return (x, y) => (x[0] != y[0])
        ? x[0].CompareTo(y[0]
        : intsList.IndexOf(x) - intsList.IndexOf(y);
}

and then the usage is simple:

array.Sort(MyCoolComparison(array));

you can of course create a comparison class implementing the IComparer interface and in the compare method implement the same logic

and use it like this:

class MyComparerClass: IComparer
{
    public int Compare(object x, object y)
    {
        // logic
    }
}
Array.Sort(array, new MyComparerClass());