트릭은 안정적인 정렬을 구현하는 것입니다. 테스트 데이터를 포함 할 수있는 위젯 클래스를 만들었습니다.
public class Widget : IComparable
{
int x;
int y;
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
public Widget(int argx, int argy)
{
x = argx;
y = argy;
}
public int CompareTo(object obj)
{
int result = 1;
if (obj != null && obj is Widget)
{
Widget w = obj as Widget;
result = this.X.CompareTo(w.X);
}
return result;
}
static public int Compare(Widget x, Widget y)
{
int result = 1;
if (x != null && y != null)
{
result = x.CompareTo(y);
}
return result;
}
}
IComparable을 구현했기 때문에 List.Sort ()에 의해 불안정하게 정렬 될 수 있습니다.
그러나 검색 메서드에 대리자로 전달할 수있는 정적 메서드 Compare도 구현했습니다.
C # 411 에서이 삽입 정렬 방법을 빌 렸습니다 .
public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
{
int count = list.Count;
for (int j = 1; j < count; j++)
{
T key = list[j];
int i = j - 1;
for (; i >= 0 && comparison(list[i], key) > 0; i--)
{
list[i + 1] = list[i];
}
list[i + 1] = key;
}
}
질문에서 언급 한 정렬 도우미 클래스에 이것을 넣을 것입니다.
이제 사용하려면 :
static void Main(string[] args)
{
List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget(0, 1));
widgets.Add(new Widget(1, 1));
widgets.Add(new Widget(0, 2));
widgets.Add(new Widget(1, 2));
InsertionSort<Widget>(widgets, Widget.Compare);
foreach (Widget w in widgets)
{
Console.WriteLine(w.X + ":" + w.Y);
}
}
그리고 다음을 출력합니다.
0:1
0:2
1:1
1:2
Press any key to continue . . .
이것은 아마도 익명의 대리인으로 정리 될 수 있지만, 나는 당신에게 맡길 것입니다.
편집 : 그리고 NoBugz는 익명 메서드의 힘을 보여줍니다 ... 그래서 더 오래된 학교를 고려하십시오 : P