踩坑
使用List.Sort(IComparer<T> comparer)进行自定义排序时,发现关键字相等的元素排序后先后顺序发生改变。检查自己实现的ICompare<T>.Compare方法逻辑没发现问题。后来查阅MSDN文档发现:
This method uses Array.Sort, which applies the introspective sort as follows:
If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm
If the number of partitions exceeds 2 log n, where n is the range of the input array, it uses a Heapsort algorithm.
Otherwise, it uses a Quicksort algorithm.
This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n2) operation.
List.Sort这个方法其实也是调用Array.Sort,而Array.Sort的内部实现主要是快速排序。
当Partition数据量较小时,使用插入排序;当Partition的数量超过 log n 时,使用堆排序。
快速排序本身是不稳定的排序算法,所以关键字相等的元素在排序后先后位置关系有可能发生改变。
解决方案
再添加一个次关键字SortIndex,这个关键字的值是排序列表元素原本的索引顺序。
对于主关键字相等的元素,再加上这个次关键字进行比较,以保证先后顺序不变。