In my code, Java TreeSet iteration is the dominant time factor. In looking at the system I believe that it is O(n) complexity. Can anyone verify this?
I am thinking that by providing links backward from child node to parent node I could improve the performance.
Iterator can be created over the TreeSet objects. Hence this iterator can be used to traverse or loop through the TreeSet.
Simply put, HashSet is faster than the TreeSet.HashSet provides constant-time performance for most operations like add(), remove() and contains(), versus the log(n) time offered by the TreeSet. Usually, we can see that the execution time for adding elements into TreeSet is much more than for the HashSet.
According to the API, TreeSet uses a TreeMap internally, which is based on a "Red-Black tree" algorithm.
TreeSet keeps the elements in order at all times. With ArrayList you just sort when you need to. With TreeSets the key must be embedded in the object you store in the collection.
TreeSet
iteration is of course O(n), as can be expect from any sensible tree-walking algorithm.
I am thinking that by providing links backward from child node to parent node I could improve the performance.
TreeMap
(which TreeSet
is based on) already has such parent references. This is the method it all boils down to:
private Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With