Implementing a generic Union-Find (Disjoint Set) in Swift is a great way to manage a collection of disjoint sets and efficiently handle union and find operations. The Union-Find data structure supports two primary operations: union, which merges two sets, and find, which identifies the representative of a set. Here’s how you can implement it in Swift.
class UnionFind {
private var parent: [T: T] = [:]
private var rank: [T: Int] = [:]
func find(_ element: T) -> T {
if parent[element] == nil {
parent[element] = element
rank[element] = 0
}
if parent[element] != element {
parent[element] = find(parent[element]!)
}
return parent[element]!
}
func union(_ element1: T, _ element2: T) {
let root1 = find(element1)
let root2 = find(element2)
if root1 != root2 {
if rank[root1]! > rank[root2]! {
parent[root2] = root1
} else if rank[root1]! < rank[root2]! {
parent[root1] = root2
} else {
parent[root2] = root1
rank[root1]! += 1
}
}
}
}
// Example Usage
let uf = UnionFind()
uf.union("A", "B")
print(uf.find("A")) // Output: A
print(uf.find("B")) // Output: A
uf.union("B", "C")
print(uf.find("C")) // Output: A
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?