Sets
A set is a data structure that can hold unique elements. It represents a mathematical set which in german is called a "Menge". This means that an element is either in the set or it isn't. Just like with a bag you have the common operations of adding elements, removing elements and searching for a specific element.
Implementing a Set
// TODO
Just like when implementing the bag we can use java.util.Arrays.binarysearch(a, from, to, key)
which returns the index of the key, if it is contained and otherwise with insertion point being the point where the key would be inserted, i.e the index of the first element greater than the key.
// TODO
Time Complexities
When implementing a set and bag there is also the question of whether the data should be sorted or not. Depending on the answer the time complexities will be different and the implementation changes.
Operation | UnsortedSet | SortedSet |
---|---|---|
add(E e) | check (search) + add | search insertion point (check) + shift right |
search(Object o) | linear search | binary search |
remove(Object o) | search + remove | search insertion point (check) + shift left |
Ideal use case | When set is needed but don't search a lot | When set is needed and a lot of searching |