2

I have an ArrayList which its elements are an Array. What I want to do is to sort this ArrayList using elements of Array. To clarify, let's suppose we have the following arraylist:

arraylist{[10,2], [6,3], [12,2]}

Then I want to sort it in descending order using dividing each elements of arrays to each other(array a_i = [a_i,b_i] ==> sort using max(a_i/b_i)), i.e., in the following form:

arraylist{[12,2],[10,2],[6,3]}

I tried using Sort(), but it is for a list not for an ArrayList as I know. Would anyone please let me know how I could sort it in an efficient way to avoid a high complexity?

Thanks!

CSDev
  • 3,177
  • 6
  • 19
  • 37
Royeh
  • 161
  • 1
  • 11

2 Answers2

3

ArrayList is deprecated and you really should not use it anymore..:

MSDN: We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List class.

Let's assume you have created a List<Tuple<int, int>> maybe like this:

var tupleList = new List<Tuple<int, int>>
{
    new Tuple<int, int>(10,2 ),
    new Tuple<int, int>(6,3),
    new Tuple<int, int>(12,2)
};

Then the result can be created with Linq, maybe like this:

var sorted = tupleList.OrderByDescending(x => x.Item1 / x.Item2);

This omits any checks for div by zero..

To make the initialization a bit shorter you can use a function..

Func<int, int, Tuple<int, int>> tc = Tuple.Create;

..taken from here and write:

var tupleList = new List<Tuple<int, int>>
{
    tc(10,2 ),
    tc(6,3 ),
    tc(12,2 )
};
TaW
  • 53,122
  • 8
  • 69
  • 111
  • In the same vein I would prefer ValueTuple over Tuple because you don’t need the class semantics of a Tuple and a ValueTuple has a much smaller footprint and more succinct syntax, i.e. `var tupleList = new List<(int dividend, int divisor)> { (10, 2), (6, 3), (12, 2) };` which also saves you defining a somewhat awkward Tuple.Create surrogate function. – ckuri Jun 08 '19 at 22:51
  • While true it takes an even newer .Net version. – TaW Jun 09 '19 at 01:06
3

Like someone said in the comments, you're better off using List<T>. But here's how to do it using Sort() with an IComparer()

class DivisionComparer : IComparer<int[]>, IComparer
{

    public int Compare(int[] x, int[] y)
    {
        double xval = (double) x[0] / x[1];
        double yval = (double) y[0] / y[1];
        return yval.CompareTo(xval);
    }

    public int Compare(object x, object y)
    {
        return Compare((int[]) x, (int[]) y);
    }
}


class Program
{

    static void Main(string[] args)
    {

        var x = new ArrayList()
        {
            new [] {6,3},                
            new [] {12,2},
            new [] {10,2},

        };
        x.Sort(new DivisionComparer());
        foreach (var el in x)
        {
            Debug.WriteLine(string.Join(",", (int[]) el));
        }
    }
}

This will output:

12,2
10,2
6,3
Nick Garyu
  • 506
  • 2
  • 5