2. Like Structures, union is a user defined data type.
In union, all members share the same memory
location.
In contrast with a record (or structure), which
could be defined to contain a float and an integer;
in a union, there is only one value at any given
time.
A union can be pictured as a chunk of memory that
is used to store variables of different data types.
3. Structures and unions. ... Each data object in
a structure is a member or field. A union is an
object similar to a structure except that all of its
members start at the same location in memory.
A union variable can represent the value of only
one of its members at a time.
Structure and union both are user defined data
types which contains variables of different data
types.
4. In union, the total memory space allocated is equal
to the member with largest size.
All other members share the same memory space.
This is the biggest difference between structure
and union.
5. There are two approaches to apply union operation:
Union by Height
Union by Weight
6. Make tree with smaller height a subtree of the
other tree
Union by Weight
The tree with fewer number of elements
becomes subtree of the other tree.
7. instead appending x to y, appending the shorter
list to the longer list.
Associated a length with each list, which
indicates how many elements in the list.
The union will at least double the length of
united set, it will take at most lg n unions to unite
n elements.
So each x’s back-to-representative pointer can be
updated at most lg n times.
8. Each node is associated with a rank, which is the
upper bound on the height of the node
i.e., the height of subtree rooted at the node
Then when union, let the root with smaller rank
point to the root with larger rank.
9. The above union() and find() are naive and the worst
case time complexity is linear. The trees created to
represent subsets can be skewed and can become like a
linked list. Following is an example worst case scenario.
The second optimization to naive method is Path
Compression. The idea is to flatten the tree
when find() is called. When find() is called for an
element x, root of the tree is returned.
The find() operation traverses up from x to find root.
The idea of path compression is to make the found root
as parent of x so that we don’t have to traverse all
intermediate nodes again. If x is root of a subtree, then
path (to root) from all nodes under x also compresses.