tags:

views:

48

answers:

2

I need to iterate both forwards and backwards in a sorted set. If I use NavigableSet, I get a strictly-forward iterator and a strictly-backward iterator (iterator() and descendingIterator()) but none that can move forward and backward.

What's the time complexity of NavigableSet.lower() and higher() ? I can use those instead, but am reluctant to do so if they are inefficient.

+1  A: 

There are only two implementations of the NavigableSet. Saying you opted for the TreeSet, while I don't have the source handy, the Javadoc says that it is based on a TreeMap providing O(log(n)) for get/put/containsKey/remove. At worst this would perform one get to find the value of we're finding the lower/higher for, plus an additional search to get the next/previous value, providing O(2log(n)) = O(log(n)).

Trees are worst case O(n) for search in the event it is actually a list, but in general, O(height).

apiri
are there trees which are faster for iteration between adjacent elements?
Jason S
It's a trade-off between operations. It depends on the size of `n`. For a tree, get is `O(log n)`, and iteration is also `O(log n)`. Using a sorted array/list, get is `O(n)`, and iteration is `O(1)`.
Andy
ok, thanks. I'm pretty sure SkipLists have O(log n) get, and O(1) iteration.
Jason S
+1  A: 

Depending on your exact needs you could convert the sorted set to a list, say an array list, and use a list iterator for traversal. It can be used in both directions via the next() and previous() methods, which may be mixed freely.

starblue
This is a fair point, and a better description of usage would help. However, at least as far as those bundled with the Java API, the only options for SortedSet (TreeSet, ConcurrentSkipListSet) are also NavigableSets. So there would just be the added time of converting to a list, and then the procedure as specified by Andy in the comment to my answer.
apiri