Digital Garden
Computer Science
Algorithms & Data Structures
Sets

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
UnsortedSet.java
// 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 ((insertionpoint)1)(-(insertion point) - 1) 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
SortedSet.java
// 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.

OperationUnsortedSetSortedSet
add(E e)O(n)O(n)
check (search) + add O(n)+O(1)O(n) + O(1)
O(n)O(n)
search insertion point (check) + shift right O(logn)+O(n)O(\log{n}) + O(n)
search(Object o)O(n)O(n)
linear search
O(logn)O(\log{n})
binary search
remove(Object o)O(n)O(n)
search + remove O(n)+O(1)O(n) + O(1)
O(n)O(n)
search insertion point (check) + shift left O(logn)+O(n)O(\log{n}) + O(n)
Ideal use caseWhen set is needed but don't search a lotWhen set is needed and a lot of searching