对 Comparer 的调用次数超出预期
不知道为什么在查看比较器的调用次数时会得到如此奇数的数字。
对于 2 个字符串:5 次调用? 另外那里有这样的序列 12 串:66 次调用 13 串:85 次调用 14 次:91 次呼叫 15 个字符串:89 个调用??????
对 15 个字符串进行排序真的比对 14 个字符串进行排序更有效吗?
int Iterations = 20;
int LastCycle = 0;
int CallsToSort = 0;
while (Iterations > 0)
{
LastCycle = CallsToSort;
CallsToSort = 0;
var strings = new string[Iterations];
for (int i = 0; i < Iterations; i++) { strings[i] = "test" + i; }
Array.Sort(strings, (s1, s2) => { CallsToSort++; return s1.CompareTo(s2); });
Console.WriteLine("Strings:{0}\nCalls to Sort: {1}\n\t\tDiff:{2}\n\n", Iterations, CallsToSort, LastCycle-CallsToSort);
Iterations--;
}
Not sure why i'd be getting such odd numbers when looking at the number of calls to the Comparer.
For 2 strings: 5 calls?
Plus there are sequences in there like this
12 Strings: 66 calls
13 Strings: 85 calls
14 Strigns: 91 calls
15 Strings: 89 calls ?????
Could it really be more efficient to sort 15 strings than 14?
int Iterations = 20;
int LastCycle = 0;
int CallsToSort = 0;
while (Iterations > 0)
{
LastCycle = CallsToSort;
CallsToSort = 0;
var strings = new string[Iterations];
for (int i = 0; i < Iterations; i++) { strings[i] = "test" + i; }
Array.Sort(strings, (s1, s2) => { CallsToSort++; return s1.CompareTo(s2); });
Console.WriteLine("Strings:{0}\nCalls to Sort: {1}\n\t\tDiff:{2}\n\n", Iterations, CallsToSort, LastCycle-CallsToSort);
Iterations--;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Array.Sort() 方法(通常)最终会使用确定性选择枢轴的 QuickSort 版本。 QuickSort 使用的比较次数在很大程度上取决于枢轴,您可以在结果中看到这一点。
一些代码(来自 ILSpy):
t
是枢轴。您可能可以准确地弄清楚为什么您会从那里看到结果。The
Array.Sort()
method will (usually) end up using a version of QuickSort where the pivots are chosen deterministically. The number of comparisons QuickSort uses will depend heavily on the pivots, and you are seeing that in your results.Some code (from ILSpy):
That
t
is the pivot. You can probably work out exactly why you see the results from there.