What is the time complexity of ordered operations in a TreeSet?

What is the time complexity of the following operations in java.util.TreeSet?

  • first()
  • last()
  • lower()
  • higher()

I would suggest that this is a constant time, but the API gives no guarantees.

+5
source share
5 answers

In fact, I would think that all these operations will be O(logN)for general implementation.

  • first() last() O(1), TreeSet . , , . , , , / ... O(logN).

  • lower() higher() , get, O(logN).

, , , . ( : . .)

+11

, first() last() O (log n), O (1) Implentation (sun jdk 1.6.0_23) TreeMap, TreeSet:

 /**
 * Returns the first Entry in the TreeMap (according to the TreeMap's
 * key-sort function).  Returns null if the TreeMap is empty.
 */
final Entry<K,V> getFirstEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.left != null)
            p = p.left;
    return p;
}

/**
 * Returns the last Entry in the TreeMap (according to the TreeMap's
 * key-sort function).  Returns null if the TreeMap is empty.
 */
final Entry<K,V> getLastEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.right != null)
            p = p.right;
    return p;
}
+1

, http://developer.classpath.org/doc/java/util/TreeSet-source.html, first() maps.firstKey() http://developer.classpath.org/doc/java/util/TreeMap-source.html

393: public K firstKey()
394: (
395: if (root == nil)
396: throw new NoSuchElementException();
397: return firstNode().key;
398: )

firstNode(), while

952: final Node<K, V> firstNode()
953: (
954: // Exploit fact that nil.left == nil.
955: Node node = root;
956: while (node.left != nil)
957: node = node.left;
958: return node;
959: )
0

API , trie. O (1), O (log n) O (n).

:

log (n) (, ).

, , , Java TreeSet.

-2

. JAVA, , - ( , , ).

, AVL , Average-Case Worst-Case O (log n) O (1).

-2

All Articles