0

I am trying to sort a list using IComparer there are about 20,000 items in my list. The first approximately 100 and last 100 items are sorted but the center is not. I am not sure what I am doing wrong. Attached is the parts of the code that does the sort.

class myclass:me
{
    private void mysort()
    {
       // Sort the data
       DistComparer dc = new DistComparer();
       st.Sort(dc);
    }
}

class DistComparer : IComparer<Tower>
{

    public int Compare(st x, st y)
    {
        double dist1 = getDistance(new PointF(45.0f, -80f), new PointF(x.Lat, x.Long));
        double dist2 = getDistance(new PointF(45.0f, -80f), new PointF(y.Lat, y.Long));
        if (dist1 > dist2)
            return 1;
        else if (dist1 == dist2)
            return 0;
        else
            return -1;
    }

    private static double getDistance(PointF pt1, PointF pt2)
    {
        return Math.Sqrt(Math.Pow((pt1.X - pt2.X), 2) + Math.Pow((pt1.Y - pt2.Y), 2));
    }
}

}

kgsw
  • 95
  • 1
  • 10
  • First off, to compare doubles equality like that is a bad idea. Use something like `else if (Math.Abs(dist1 - dist2) < 0.000001)`. – bashis Jan 29 '16 at 15:54
  • 4
    If you're really using lattitude ang longtitude (as I can guess from the variable names) - you can't directly calculate distance in such a way. The reason is lattitude and longtitude are coordinates on geoid, not in cartesian coordinate system - so formula you've used will calculate distance incorrectly. – Andrey Korneyev Jan 29 '16 at 15:55
  • 1
    I ran your code and tested it against 500 random float values and it appears to sort properly. I spot checked but I didn't notice anything that was wrong? Keep in mind you are sorting off distance which means your actual post sort list might have lat or long numbers that jump around. Are you saying that your distances are being sorted improperly? – Jarrett Robertson Jan 29 '16 at 16:26

0 Answers0