A stable sort is a sort that maintains the relative order of elements with the same value.
The ArrayList.Sort docs say that under the condition of IComparer sorting is stable:
If the comparison parameter is set to null, this method performs sorting (also called unstable sorting); that is, if two elements are equal, their order may not be preserved. In contrast, robust sorting preserves the order of equal elements. To perform stable sorting, you must implement the IComparer user interface.
If I didn’t miss something, the following test case shows that ArrayList.Sort does not use a stable view:
internal class DisplayOrdered { public int ID { get; set; } public int DisplayOrder { get; set; } public override string ToString() { return string.Format("ID: {0}, DisplayOrder: {1}", ID, DisplayOrder); } } internal class DisplayOrderedComparer : IComparer { public int Compare(object x, object y) { return ((DisplayOrdered)x).DisplayOrder - ((DisplayOrdered)y).DisplayOrder; } } [TestFixture] public class ArrayListStableSortTest { [Test] public void TestWeblinkCallArrayListIsSortedUsingStableSort() { var call1 = new DisplayOrdered {ID = 1, DisplayOrder = 0}; var call2 = new DisplayOrdered {ID = 2, DisplayOrder = 0}; var call3 = new DisplayOrdered {ID = 3, DisplayOrder = 2}; var list = new ArrayList {call1, call2, call3}; list.Sort(new DisplayOrderedComparer());
Am I missing something? If not, will it be a documentation error or a library error?
Using OrderBy in Linq seems to give a stable look.
Kaleb pederson
source share