Does anyone know what the time complexity of java.util.stream.Stream<T>.sorted()
is?
Asked
Active
Viewed 1.1k times
21

templatetypedef
- 362,284
- 104
- 897
- 1,065

hackie
- 323
- 1
- 2
- 6
-
Well, `Stream` is an interface. It depends solely on the implementation. – Obicere Jul 08 '15 at 19:22
2 Answers
32
Well, sorted()
in itself is O(1), since it's an intermediate operation that doesn't consume the stream, but simply adds an operation to the pipeline.
Once the stream is consumed by a terminal operation, the sort happens and either
- it doesn't do anything (O(1)) because the stream knows that the elements are already sorted (because they come from a SortedSet, for example)
- or the stream is not parallel, and it delegates to
Arrays.sort()
(O(n log n)) - or the stream is parallel, and it delegates to
Arrays.parallelSort()
(O(n log n))

Richard Lewan
- 222
- 3
- 7

JB Nizet
- 678,734
- 91
- 1,224
- 1,255
8
As of JDK 8, the main sorting algorithm which is also used in standard stream API implementation for sequential sorting is TimSort. Its worst case is O(n log n)
, but it works incredibly fast (with O(n)
and quite small constant) if data is presorted (in forward or reverse direction) or partially presorted (for example, if you concatenate two sorted lists and sort them again).

Tagir Valeev
- 97,161
- 19
- 222
- 334