110,537
社区成员
发帖
与我相关
我的任务
分享
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("1474");
list.Add("1.1");
list.Add("881");
list.Add("wg");
list.Add("d90");
list.Add("json");
list.Sort(new ASCIIStringCompare());
}
}
public class ASCIIStringCompare : IComparer<string>
{
public int Compare(string x, string y)
{
if (x.Length==0)
{
return -1;
}
if (y.Length==0)
{
return 1;
}
if ((int)x.First()==(int)y.First())
{
return Compare(x.Substring(1), y.Substring(1));
}
return ((int)x.First()).CompareTo((int)y.First());
}
}
public class ASCIIStringCompare : IComparer<string>
{
public int Compare(string x, string y)
{
if (x.CompareTo(y) == 0)
{
return 0;
}
if (x.Length == 0)
{
return -1;
}
if (y.Length == 0)
{
return 1;
}
if ((int)x.First() == (int)y.First())
{
return Compare(x.Substring(1), y.Substring(1));
}
return ((int)x.First()).CompareTo((int)y.First());
}
}
好像这样就可行了list.Sort(StringComparer.Ordinal);
var q = list.OrderBy(x => x);
这样不行吗?list.Sort(StringComparer.Ordinal);
4.0自定义的为什么会有问题
if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
{
ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer);
}
else
{
ArraySortHelper<T>.DepthLimitedQuickSort(keys, index, (length + index) - 1, comparer, 0x20);
}
4.5 的说明:
This method uses the Array.Sort method, which applies the introspective sort as follows:
If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.
If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.
Otherwise, it uses a Quicksort algorithm. (参考:https://msdn.microsoft.com/en-us/library/b0zbh7b6(v=vs.110).aspx)
示例代码的排序次数:插入排序
[ 1 ] 1.1 vs 1474
[ 2 ] .1 vs 474
[ 3 ] 881 vs 1474
[ 4 ] wg vs 881
[ 5 ] d90 vs wg
[ 6 ] d90 vs 881
[ 7 ] json vs wg
[ 8 ] json vs d90
而低版本的示代码的排序次数:
[ 1 ] 1474 vs 881
[ 2 ] 1474 vs json
[ 3 ] 881 vs json
[ 4 ] 1474 vs 881
[ 5 ] 1.1 vs 881
[ 6 ] 881 vs 881
[ 7 ] 81 vs 81
[ 8 ] 1 vs 1
[ 9 ] vs
[ 10 ] wg vs 881
[ 11 ] 881 vs json
[ 12 ] 881 vs d90
[ 13 ] 881 vs wg
[ 14 ] 881 vs 881
[ 15 ] 81 vs 81
[ 16 ] 1 vs 1
[ 17 ] vs
[ 18 ] 881 vs 1.1
[ 19 ] 1474 vs 1.1
[ 20 ] 474 vs .1
[ 21 ] 1.1 vs 1474
[ 22 ] .1 vs 474
[ 23 ] 1.1 vs 1.1
[ 24 ] .1 vs .1
[ 25 ] 1 vs 1
[ 26 ] vs
[ 27 ] 1474 vs 1.1
[ 28 ] 474 vs .1
[ 29 ] 1.1 vs 1474
[ 30 ] .1 vs 474
[ 31 ] 1.1 vs 1.1
[ 32 ] .1 vs .1
[ 33 ] 1 vs 1
[ 34 ] vs
自己看下源码: (其实我没太懂)
http://referencesource.microsoft.com/#mscorlib/system/collections/generic/arraysorthelper.cs,63a9955a91f2b37b
比较的顺序很随机,很可能出现自己和自己比较情况。 而低版本排序是由递归实现的DepthLimitedQuickSort, 次数是有限制的,其实后面还没有比较完就已经结束了。 “if (x.CompareTo(y) == 0) return 0; //如果是自己与自己比较” ,避免了问题。
还是5楼的更好: list.Sort(StringComparer.Ordinal);list.OrderBy(o => o).ToList()
list.OrderBy(arr => arr[0]).ToList();
用Linq好像可以