The code first takes the nearest point to (0, 0) at the '0' index then start sorting the points by distance from the last spotted point..
C#:
List<Point> SortByDistance(List<Point> lst)
{
List<Point> output = new List<Point>();
output.Add(lst[NearestPoint(new Point(0, 0), lst)]);
lst.Remove(output[0]);
int x = 0;
for (int i = 0; i < lst.Count + x; i++)
{
output.Add(lst[NearestPoint(output[output.Count - 1], lst)]);
lst.Remove(output[output.Count - 1]);
x++;
}
return output;
}
int NearestPoint(Point srcPt, List<Point> lookIn)
{
KeyValuePair<double, int> smallestDistance = new KeyValuePair<double, int>();
for (int i = 0; i < lookIn.Count; i++)
{
double distance = Math.Sqrt(Math.Pow(srcPt.X - lookIn[i].X, 2) + Math.Pow(srcPt.Y - lookIn[i].Y, 2));
if (i == 0)
{
smallestDistance = new KeyValuePair<double, int>(distance, i);
}
else
{
if (distance < smallestDistance.Key)
{
smallestDistance = new KeyValuePair<double, int>(distance, i);
}
}
}
return smallestDistance.Value;
}
VB.Net:
Function SortByDistance(ByVal lst As List(Of Point)) As List(Of Point)
Dim out As New List(Of Point)
out.Add(lst(NearestPoint(New Point(0, 0), lst)))
lst.Remove(out(0))
Dim x As Integer = 0
For i As Integer = 0 To lst.Count - 1 + x
out.Add(lst(NearestPoint(out(out.Count - 1), lst)))
lst.Remove(out(out.Count - 1))
x += 1
Next
Return out
End Function
Function NearestPoint(ByVal srcPt As Point, ByVal lookIn As List(Of Point)) As Integer
Dim smallestDistance As KeyValuePair(Of Double, Integer)
For i As Integer = 0 To lookIn.Count - 1
Dim distance As Double = Math.Sqrt(Math.Pow(srcPt.X - lookIn(i).X, 2) + Math.Pow(srcPt.Y - lookIn(i).Y, 2))
If i = 0 Then
smallestDistance = New KeyValuePair(Of Double, Integer)(distance, i)
Else
If distance < smallestDistance.Key Then
smallestDistance = New KeyValuePair(Of Double, Integer)(distance, i)
End If
End If
Next
Return smallestDistance.Value
End Function