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)
), ie, 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!
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 )
};
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
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.