140 likes | 423 Views
The Design and Analysis of Algorithms. Chapter 9: Union-Find Algorithms. Union-Find Algorithms. Basic Idea Quick Find Quick Union Path Compression. Basic Idea. Initialization: each disjoint subset is one-element subset, containing a different element of S .
E N D
The Design and Analysis of Algorithms Chapter 9:Union-Find Algorithms
Union-Find Algorithms • Basic Idea • Quick Find • Quick Union • Path Compression
Basic Idea • Initialization: each disjoint subset is one-element subset, containing a different element of S. • Union-find operation: acts on the collection of n one-element subsets to give larger subsets.
Abstract data type for the finite set • makeset(x)- creates an one-element set {x} • find(x) - returns a subset containing x • union(x,y) - constructs the union of disjoint subsets Sx and Sy containing xand y, and adds it to the collection. Sxand Sy are deleted from the collection
Subset’s representative • Use one element from each of the disjoint subsets in a collection • Two principal implementations • Quick find • Quick union
Quick Find • Record the representatives for each element in an array R[k] = k if k is a representative of some set R[k] = m if k is in a set with representative m • The sets are stored in lists whose heads are in an array heads[1..N] • If k is a representative of a set, then heads[k] contains a reference to a list with the elements of that set • If k is not a representative of a set, heads[k] is null
Find(x) operation • To find the representative of an element we simply check the array with the representatives – (1)
Union(x,y) operation • A find(x) • B find(y) • Attach the one of the lists to the other: • A[last].next B[first] • A[last] B[last] • Update the representatives of the attached set
Union(x,y) Efficiency • (N)worst time for one union operation • (N2)for union (2,1), union (3,2), … union (n, n-1) • union-by size: attach the smaller set to the larger set • worst case is still (N), average case for a sequence of N-1 union operations isO(NlogN)
1 1 1 2 2 2 3 6 6 6 3 3 4 4 4 5 5 5 Quick Union • Update only the representative of one of the sets (the smaller set) • O(N + m logN) Given the subsets {1,6}, {2, 4}, {3, 5}, after union(2,5) we obtain: In Quick Find R = 1, 2, 2, 2, 2, 1 In Quick Union R = 1, 2, 2, 2, 3, 1
Path Compression • Make every element encountered during the find to point to the root of the tree. Efficiency: slightly worse than linear.