Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to SortedSet<T> and its complexity

MSDN states the following SortedSet(T).Add Method :

If Count is less than the capacity of the internal array, this method is an O(1) operation.

Could someone please explain "how so"? I mean when adding new value we need to find a correct place to add a value (comparing it with another values) and internal implementation looks like a "Red-Black tree" with O (log N) insertion complexity.

like image 566
Andrey Taptunov Avatar asked Mar 28 '10 13:03

Andrey Taptunov


People also ask

What is the time complexity for a Sorted List?

SortedList provides O(log n) time complexity for KeyValuePair retrieval. Unlike SortedDictionary that is implemented with Binary Search Tree, SortedList is implemented with two internal arrays for keys and values. Therefore, insertion operation and removal operation take O(n), which are slower than SortedDictionary.

What is SortedSet in C#?

In C#, SortedSet is a collection of objects in sorted order. It is of the generic type collection and defined under System. Collections. Generic namespace. It also provides many mathematical set operations, such as intersection, union, and difference.

How does a sorted set work?

A set is used to provide a particular ordering on its element. The elements are ordered either by using a natural ordering or by using a Comparator. All the elements which are inserted into a sorted set must implement the Comparable interface. The set's iterator will traverse the set in an ascending order.

What is sorted set?

A SortedSet is a Set that maintains its elements in ascending order, sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet creation time.


1 Answers

The comment is simply wrong. Yes, it is a red-black tree, O(log(n)) for inserts. Taking a look with Reflector bears this out, the private AddIfNotPresent() method contains a while() loop to find the insertion point, using normal red-black node traversal.

This doc bug has already been submitted by you-know-who.

like image 56
Hans Passant Avatar answered Sep 28 '22 17:09

Hans Passant