对于已经排序的2百万个元素数组,Arrays.sort(...)的效率如何

时间:2014-06-12 16:30:31

标签: java arrays performance sorting

我需要使用Arrays.sort(..)方法对包含2百万个元素的数组执行另一个排序。为了不再保留另一个脏标志,我想知道这个方法调用已经排序的数组的代价是多少。

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

这取决于数组的内容。排序基元使用双轴快速排序as per the docs。这具有O(n logn)的摊销复杂性,但最坏的情况是O(n^2)

排序对象使用TimSortdocs),修改后的合并排序。 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

For Object [] array

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)。