Docsity

Implementing Disjoint Sets: A Data Structure for Maintaining Collections of Sets - Prof. D, Study notes of Algorithms and Programming

Partial preview of the text

Download Implementing Disjoint Sets: A Data Structure for Maintaining Collections of Sets - Prof. D and more Study notes Algorithms and Programming in PDF only on Docsity!

Graduate Algorithms^ CS673-2008F-14Disjoint Sets^ David GallesDepartment of Computer ScienceUniversity of San Francisco

14-0:^ Disjoint Sets^ Maintain a collection of sets^ Operations:^ Determine which set an element is in^ Union (merge) two sets^ Initially, each element is in its own set^ # of sets = # of elements

14-2:^ Disjoint Sets^ Implementing Disjoint sets^ How should disjoint sets be implemented?

14-3:^ Implementing Disjoint Sets^ Implementing Disjoint sets (First Try)^ Array of set identifiers:Set[i] = set containing element i^ Initially, Set[i] = i

14-5:^ Implementing Disjoint Sets^ Creating sets: (pseudo-Java) void CreateSets(n) {for (i=0; i<n; i++) {Set[i] = i;} }

14-6:^ Implementing Disjoint Sets^ Find:

14-8:^ Implementing Disjoint Sets^ Union:

14-9:^ Implementing Disjoint Sets^ Union: (pseudo-Java) void Union(x,y) {set1 = Set[x];set2 = Set[y];for (i=0; i < n; i=+)if (Set[i] == set2)Set[i] = set1;}

14-11:^ Disjoint Sets

CreateSets:^ ฮ˜(n) Find:^ ฮ˜(1) Union:^ ฮ˜(n)

14-12:^ Disjoint Sets

CreateSets:^ ฮ˜(n) Find:^ ฮ˜(1) Union:^ ฮ˜(n) We can do better! (At least for Union ...)

14-14:^ Implementing Disjoint Sets II^ Store elements in trees^ All elements in the same set will be in the sametree^ Find(x) returns the element at the root of the treecontaining x^ How can we easily find the root of a treecontaining x?^ Implement trees using

parent pointers^ instead of^ children pointers

14-15:^ Trees Using Parent Pointers^ Examples:^12 34 5

7

1 2 3 4 5 6 7

14-17:^ Implementing Disjoint Sets II^ Each element is represented by a node in a tree^ Maintain an array of pointers to nodes^1

(^3 4 5 )

7 8 (^5041 2 ) 6 7 8

14-18:^ Implementing Disjoint Sets II^ Find: