Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big-O complexity of java.util.stream.Stream<T>.sorted()

Tags:

Does anyone know what the time complexity of java.util.stream.Stream<T>.sorted() is?

like image 346
hackie Avatar asked Jul 08 '15 19:07

hackie


People also ask

What is the time complexity of streams in Java?

It is O(n) . The stream filtering uses iteration internally. But, that conversion process is also O(n).

Is Java Stream sorted?

Stream sorted() in JavaStream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.

What is Stream of () Stream Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

Which method is used to sort the Stream?

Java Stream sorted() Learn to use Stream sorted() method to sort the elements in a Stream by their natural order.


2 Answers

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))
like image 125
JB Nizet Avatar answered Oct 29 '22 22:10

JB Nizet


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

like image 35
Tagir Valeev Avatar answered Oct 29 '22 23:10

Tagir Valeev