Docsity

Dynamic Equivalence Problem, Parent Array - Data Stuctures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Dynamic Equivalence Problem, Parent Array - Data Stuctures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Dynamic Equivalence Problem

 We will use a tree to represent each set,

since each element in a tree has the same

root.

 The root can be used to name the set.

 There will be a collection of trees, each

tree representing one set. A collection of

trees is called a forest.

Dynamic Equivalence Problem

 The trees we will use are not necessarily

binary.

 To perform union of two sets, we merge

the two trees by making the root of one

point to the root of the other.

 A find ( x ) on element x is performed by

returning the root of the tree containing x.

Dynamic Equivalence Problem

After union(5,6)

Dynamic Equivalence Problem

After union(7,8)

Dynamic Equivalence Problem

After union(3,4)

Dynamic Equivalence Problem

After union(4,5)

Dynamic Equivalence Problem

Initialization:

for (i=0; i < n; i++)

parent[i] = -1;

find(i):

// traverse to the root (-1)

for(j=i; parent[j] >= 0; j=parent[j])

return j;

Dynamic Equivalence Problem

union(i,j):

root_i = find(i);

root_j = find(j);

if (root_i != root_j)

parent[root_j] = root_i;

Parent Array

After union(5,6)

Parent Array

After union(7,8)

Parent Array

After union(3,4)

Parent Array

After union(4,5)

Running Time Analysis

 Union is clearly a constant time operation.

 Running time of find ( i ) is proportional to

the height of the tree containing node i.

 This can be proportional to n in the worst

case (but not always)

 Goal: Modify union to ensure that heights

stay small