

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


COMPSCI 342: Data Structures and Algorithms
We want to maintain n distinct elements as a collection of disjoint sets. Each set is identified by a representative, which is some member of the set. The three operations are:
Makeset(x) Create a new set whose only member is pointed to by x. Since the sets are disjoint we require that x not already be in a pre-existing set.
Find(x) Return a pointer to the representative of the unique set containing x.
Union(x, y) Unite the dynamic sets represented by x and y into a new set that is the union of the two original sets. The original sets are destroyed.
We always have n Makeset() operations, at most n − 1 Union() operations and have m Find() operations, where m ≥ n. The goal is to design a data structure that will support this sequence of the three operations as efficiently as possible. The runtime will be analyzed for the whole sequence of operations rather than one operation at a time. (This is an example of amortized analysis.)
The elements are from the set 1, 2 ,... , n. set[1..n]: set[i] is the label of the set to which element i belongs.
The array set[1..n] is the only data structure that this initial attempt uses.
Makeset(x)
Find1(x)
Union1(x,y)
The worst-case runtime is Θ(m + n^2 ).
Represent each set by a linked list. Each cell has a next pointer and a pointer to the beginning of the list. The label of a set is the label of the first element in the linked list.
Pseudo-code formulation left as an exercise.
Use trees to represent sets. We will use the parent-pointer representation of trees. This makes union really simple but find becomes harder.
Analogy: Someone changing addresses— instead of notifying everyone, it is simpler to leave a forwarding address. But this means that finding the right address takes more steps.
parent[1..n]: parent[i] is the parent of element i in the tree representing the set to which element i belongs.
Makeset(x)
Find3(x)
Union3(x,y)
The worst-case runtime is Θ(mn).
Now we attempt to balance the trees with the heuristic that the smaller tree is merged with the larger tree. We keep track of the number of elements in the tree in the array size[1..n].
Makeset(x)
Union4(x,y)
Another balancing strategy is to use the heights of the trees to perform the union. Suppose we keep track of the heights of the trees in the array height[1..n]. Then we can make the shorter tree be a subtree of the taller tree. The height only increases if the two trees being union-ed have the same height. The pseudo-code is left as an exercise.
The worst-case runtime for either balancing technique is Θ(m lg n).