Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List<Tuple<int, int>> in-place

Tags:

c#

list

sorting

How would I go about sorting in descending order, a List<Tuple<int, int>> using the first element of the tuple as the value that determines the order? It has to be in-place and I only know how to do it using LINQ which returns a new list.

like image 815
BobTurbo Avatar asked Jan 12 '11 11:01

BobTurbo


People also ask

How do you sort a list with a tuple?

In python, to sort list of tuples by the first element in descending order, we have to use the sort() method with the parameter ” (reverse=True) “ which will sort the elements in descending order.

How do you sort a tuple in Python without sorting?

You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.

How do I sort a Python list in reverse order?

In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.


2 Answers

You just need to provide an IComparer<Tuple<int, int>> or a Comparison<Tuple<int, int>> to the List<T>.Sort method. The latter is probably easier to specify inline:

list.Sort((x, y) => y.Item1.CompareTo(x.Item1));

If you want to order by the first value and then the second value, it becomes a bit trickier, but still feasible. For example:

list.Sort((x, y) => {
    int result = y.Item1.CompareTo(x.Item1);
    return result == 0 ? y.Item2.CompareTo(x.Item2) : result;
});

EDIT: I've now amended the above to sort in descending order. Note that the right way to do this is to reverse the order of the comparison (y to x instead of x to y). You must not just negate the return value of CompareTo - this will fail when CompareTo returns int.MinValue.

like image 79
Jon Skeet Avatar answered Sep 26 '22 06:09

Jon Skeet


Why not this?

List<Tuple<int, int>> list = ...
list = list.OrderBy(i => i.Item1).ToList();

Yes, it creates a new list, but I'm just interested - why don't you like this?


List<Tuple<int, int>> list = new List<Tuple<int, int>>
{
    new Tuple<int,int>(1,1),
    new Tuple<int,int>(0,2),
    new Tuple<int,int>(3,0)
};

list.Sort(Comparer<Tuple<int, int>>.Default);

produces:

0,2
1,1
3,0

And it's in-place, isn't it?

like image 16
abatishchev Avatar answered Sep 28 '22 06:09

abatishchev