我需要使用Arrays.sort(..)方法对包含2百万个元素的数组执行另一个排序。为了不再保留另一个脏标志,我想知道这个方法调用已经排序的数组的代价是多少。
有什么想法吗?
答案 0 :(得分:2)
这取决于数组的内容。排序基元使用双轴快速排序as per the docs。这具有O(n logn)
的摊销复杂性,但最坏的情况是O(n^2)
排序对象使用TimSort(docs),修改后的合并排序。 According to the docs,TimSort对于近似排序(或者,可能是已排序)的数组进行大约n
次比较。
如果保持脏旗而不是遭受O(n)
比较,那还会便宜得多。
答案 1 :(得分:0)
Best case performance O(n log n)
Worst case performance O(n2)
有关详细信息,请参阅:http://en.wikipedia.org/wiki/Quicksort
Worst case performance O(n log n)
Best case performance O(n)
有关详细信息,请参阅:http://en.wikipedia.org/wiki/Timsort
答案 2 :(得分:-1)
Per this thread,排序运行时将为O(n*log n)
,因为Arrays.sort()
使用了quicksort的修改版本,无论数组是否已经排序。
答案 3 :(得分:-1)
Array.sort()使用O(n log n)的最佳案例复杂性场景,通过使用Merge Sort对数组进行排序,而Merge Sort又使用了分而治之的方法。在已经有排序数组的最佳情况下,最佳可能情况可能是O(n)。