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

前端 未结 2 1811
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 20:12

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 20:56

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

提交回复
热议问题