Sort points vertically, then horizontally

I have an array Points

and I want to sort it both vertically and horizontally.

Should I sort twice?

+2


source to share


4 answers


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

What you need to do is implement a custom IComparer for the class you are trying to sort and use for comparison 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;
        }
    }
}

      



Using:

List<Point> list = ...;
list.Sort(new PointComparer());

      

+13


source


Using LINQ for Objects:



using System;
using System.Linq;
using System.Drawing;

class Example
{
    static void Main()
    {
        Point[] points = new Point[] 
        { 
            new Point(2,2),
            new Point(3,1),
            new Point(3,2),
            new Point(1,3)
        };

        var sortedPoints = points
                .OrderBy(p => p.X)
                .ThenBy(p => p.Y);
    }
}

      

+4


source


0


source


I can't tell from the question if by "sort both vertically and horizontally" you want to sort them "first vertically then horizontally" (best done in one pass as other answers have said), or if you want to sort them so that the adjacent points in the plane are usually in the list. If it is the latter, there is a curve filling gap , which can be much better than a pure approach with vertical and then horizontal.

0


source







All Articles