Ada U2 Notes
Ada U2 Notes
UNIT-II
Disjoint Sets: Disjoint set operations, union and find algorithms
Disjoint Sets: If Si and Sj, i≠j are two sets, then there is no element that is
in both Si and Sj.. For example: n=10 elements can be partitioned into three
disjoint sets,
S1= {1, 7, 8, 9}
S2= {2, 5, 10}
S3= {3, 4, 6}
Find(4)->S3
Find(1)->S1
Find(10)->S2
Tress can be accomplished easily if, with each set name, we keep a pointer
to the root of the tree representing that set.
For presenting the union and find algorithms, we ignore the set names and
identify sets just by the roots of the trees representing them.
For example: if we determine that element ‘i’ is in a tree with root ‘j’ has a
pointer to entry ‘k’ in the set name table, then the set name is just name[k]
Example: If you wish to unite to Si and Sj then we wish to unite the tree
with roots
FindPointer is a function that takes a set name and determines the root of
the tree that represents it.
Find(i)-1st determine the root of the tree and find its pointer to entry in
setname table.
Union(i, j)-Means union of two trees whose roots are i and j.
P[1:n].
i 1 2 3 4 5 6 7 8 9 10
P -1 5 -1 3 -1 3 1 1 1 5
Algorithm
Algorithm Simpleunion(i, j)
Example: Find(6) start at 6 and then moves to 6’s parent. Since P[3] is
negative, we reached the root.
Algorithm SimpleFind(i)
while(P[i]≥0) do i:=P[i];
return i;
If n numbers of roots are there then the above algorithms are not useful for
union and find.
Time taken for the union (simple union) is -> O(1) (constant).
If the number of nodes in the tree with root ‘i’ is less than the tree with root
‘j’, then make ‘j’ the parent of ‘i’; otherwise make ‘i’ the parent of ‘j’.
Algorithm WeightedUnion(i,j)
temp := p[i]+p[j];
if (p[i]>p[j]) then
P[i]:=j;
P[j]:=temp;
}
else
P[j] := i;
P[i] := temp;
For implementing the weighting rule, we need to know how many nodes
there are in every tree.
For this we maintain a count field in the root of every tree.
i->root node
count[i]->number of nodes in the tree.
Time required for this above algorithm is O(1) + time for remaining
unchanged is determined by using Lemma.
Collapsing rule: If ‘j’ is a node on the path from ‘i’ to its root and p[i]≠root[i],
then set p[j] to root[i].
Algorithm CollapsingFind(i)
r;=i;
s:=p[i];
p[i]:=r;
i:=s;
}
return r;
If SimpleFind is used, each Find(8) requires going up three parent link fields
for a total of 24 moves to process all eight finds.
When CollapsingFind is used the first Find(8) requires going up three links
and then resetting two links. Total 13 moves requires for process all eight
finds.