It uses the Quicksort algorithm, which is unstable when deployed efficiently (in place). This means that it does not guarantee that equal values ββretain their previous relative position after sorting.
For example, if you have a bunch of dots:
Point[] points = new Point[] { new Point(0, 1), new Point(0, 2), new Point(0, 3), new Point(1, 1), new Point(1, 2), new Point(1, 3) };
And you only sort these points by the x coordinate using this comparator:
private int CompareByX(Point a, Point b) { return aX - bX; }
This only guarantees that the points are sorted by their x coordinate, that is, you can easily get a mixed order (when viewing the y-coordinate):
Point(0, 3) Point(0, 2) Point(0, 1) Point(1, 3) Point(1, 2) Point(1, 1)
[change]
This does not mean that the sorting algorithm is not deterministic (random). For the same input, you get the same output for each run. You can also predict exactly how it will be reorganized if you study the algorithm exactly, but it is not necessary. Just know that this happens when using the sorting procedure.
Here is a working example of your problem, try resizing the test data (first line in Main ) and see how the array is reorganized in each run:
class Program { static void Main() { Point[] points = CreateTestData(1, 4).ToArray(); DisplayItems("Before", points); Array.Sort(points, CompareByX); DisplayItems("After", points); Console.ReadLine(); } private class Point { public int X { get; private set; } public int Y { get; private set; } public override string ToString() { return string.Format("({0},{1})", X, Y); } public Point(int x, int y) { X = x; Y = y; } } private static int CompareByX(Point a, Point b) { return aX - bX; } private static IEnumerable<Point> CreateTestData(int maxX, int maxY) { for (int x = 0; x <= 1; x++) for (int y = 0; y <= 4; y++) yield return new Point(x, y); } private static void DisplayItems(string msg, Point[] points) { Console.WriteLine(msg); foreach (Point p in points) Console.WriteLine(p.ToString()); Console.WriteLine(); } }
Of course, if you expand the delegate comparator to include the Y coordinate, you will not have this problem:
private static int CompareByX(Point a, Point b) { if (aX == bX) return aY - bY; else return aX - bX; }