关于Java:Arrays.sort()是否会增加时间复杂度和时空复杂度?

Will Arrays.sort() increase time complexity and space time complexity?

存在与阵列相关的问题,要求时间复杂度为O(n),空间复杂度为O(1)。

如果我使用Arrays.sort(arr),并使用一个for循环到一个循环,例如:

1
2
3
4
5
6
public static int hello(int[]A){
  Arrays.sort(A);
  for(int i=0;i<A.length;i++){
     ....................
  }
  return ....;

}

因此,循环将花费O(n)时间。 我的问题是:Arrays.sort()会花费更多时间吗? 如果使用Arrays.sort(),则此时间复杂度是否仍为O(n)? 并且Arrays.sort()会占用更多空间吗?


我假设您在这里谈论Java。

So the loop will cost O(n) time, my question is that will Arrays.sort() cost more time?

是的,我所知道的所有Java标准库实现中的Arrays.sort(int[])都是基于比较的排序的示例,因此必须具有最坏情况的复杂度Ω(n log n)。特别是,Oracle Java 7对整数重载使用了双数据点快速排序变体,实际上这是Ω(n2)最坏的情况。

and will Arrays.sort() cost more space?

它极有可能会使用ω(1)空间(这意味着另一个是,空间使用量不是O(1))。虽然只用恒定的额外空间来实现基于比较的排序并不是不可能的,但这是非常不切实际的。

也就是说,在某些情况下,可以在线性时间内对特定类型的数据进行排序,例如:

  • http://en.wikipedia.org/wiki/Counting_sort
  • http://en.wikipedia.org/wiki/Pigeonhole_sort
  • http://en.wikipedia.org/wiki/Radix_sort

对于恒定的输入整数范围(例如,如果abs(A[i]) <= C对于某个常数C),则计数排序和基数排序实际上仅使用O(n)时间和O(1)空间,因此这可能很有用。


根据Arrays.sort()方法的java jvm 8 javadocs:

排序算法是Vladimir Yaroslavskiy,Jon Bentley和Joshua Bloch编写的Dual-Pivot Quicksort。该算法可在许多数据集上提供O(n log(n))性能,从而导致其他快速排序降级为二次性能,并且通常比传统的(单轴)Quicksort实现要快。

因此,它将使您的时间复杂度从O(n)增加到O(n log(n))


它超过O(n)时间,并且需要超过O(1)空间。

Arrays.sort()在1.7中使用了经过改进的Timsort,这是一种相对较新开发的排序算法,它提供了复杂度为x的排序,其中O(n)


最近的JDK中的Arrays.sort(int [] a)是通过Dual-pivot Quicksort算法实现的,该算法的平均复杂度为O(n log n),并且可以就地执行(例如,不需要额外的空间)。