Computational complexity of TreeSet operations in Java?

后端 未结 4 1419
暗喜
暗喜 2021-01-04 17:43

I am trying to clear up some things regarding complexity in some of the operations of TreeSet. On the javadoc it says:

\"This implementation provides

相关标签:
4条回答
  • 2021-01-04 17:59

    It is not possible to perform merging of trees or join sets like in Disjoint-set data structures because you don't know if the elements in the 2 trees are disjoint. Since the data structures have knowledge about the content in other trees, it is necessary to check if one element exists in the other tree before adding to it or at-least trying to add it into another tree and abort adding it if you find it on the way. So, it should be O(MlogN)

    0 讨论(0)
  • 2021-01-04 18:06

    You could imagine how it would be possible to optimize special cases to O(log n), but the worst case has got to be O(m log n) where m and n are the number of elements in each tree.

    Edit:

    http://net.pku.edu.cn/~course/cs101/resource/Intro2Algorithm/book6/chap14.htm

    Describes a special case algorithm that can join trees in O(log(m + n)) but note the restriction: all members of S1 must be less than all members of S2. This is what I meant that there are special optimizations for special cases.

    0 讨论(0)
  • 2021-01-04 18:12

    According to this blog post:
    http://rgrig.blogspot.com/2008/06/java-api-complexity-guarantees.html
    it's O(n log n). Because the documentation gives no hints about the complexity, you might want to write your own algorithm if the performance is critical for you.

    0 讨论(0)
  • 2021-01-04 18:15

    Looking at the java source for TreeSet, it looks like it if the passed in collection is a SortedSet then it uses a O(n) time algorithm. Otherwise it calls super.addAll, which I'm guessing will result in O(n logn).

    EDIT - guess I read the code too fast, TreeSet can only use the O(n) algorithm if it's backing map is empty

    0 讨论(0)
提交回复
热议问题