Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Points vertically then horizontally

Tags:

c#

sorting

I have an array of Points and i want to sort then both vertically and horizontally.

Should I sort twice?


1 Answers

No you can't just sort twice because the .Net framework Sort() algorithm is an unstable sort, which means that when you sort items, the order they originaly were in is not taken into account, that is, when two items are equal, their position relative to each other will be undefined.

What you will need to do is implement a custom IComparer for the class you are trying to sort and use that comparer when sorting your collection:

class PointComparer : IComparer<Point>
{
    public int Compare(Point x, Point y)
    {
        if (x.Y != y.Y)
        {
            return x.Y - y.Y;
        }
        else
        {
            return x.X - y.X;
        }
    }
}

Usage:

List<Point> list = ...;
list.Sort(new PointComparer());
like image 164
Coincoin Avatar answered Nov 28 '25 12:11

Coincoin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!